OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How can update the step form view with Ajax in ASP.NET

  • Thread starter Thread starter Maryam12 forex
  • Start date Start date
M

Maryam12 forex

Guest
this is my method to Get Cart:

Code:
   [HttpGet("/UserPanel/CheckOut")]
   public async Task<IActionResult> CheckOut()
   {


       var text = await _siteService.GetSiteSettingForEdit();
       var tax = text.Tax;

       var userId = User.GetCurrentUserId();

       // Get From Session
       var cartItems = _orderService.GetFromSession();

       // Update ClientId In ShowCart after Login
       foreach (var item in cartItems)
       {
           if (item.ClientId == 0)
           {
               item.ClientId = userId;
           }
       }


       // Get user addresses
       var userAddresses = await _orderService.GetClientContactInfoById(userId);

       

       // we check it in repo and create a list:
       //    List<CartAddressViewModel> cartAddresses = new List<CartAddressViewModel>();
       //so we don't need to check if null, because in repo 100% create a list for it with object, but not null



       var deliveryAndPaymentDetails = GetDeliveryAndPaymentDetailsFromSession();
       //First get 0/0/1 then after run 2 script it will  be change to the new date

       // Create CartViewModel

       var cartViewModel = new CartViewModel
       {
           Items = cartItems,
           Tax = tax,
           CartAddresses = userAddresses,
           CartDeliveryDateViewModel = deliveryAndPaymentDetails

       };


       await GetStateAndDistricts();

       return View(cartViewModel);
   }

and I Add New Address in form 2 in my stepform :

Code:
      [HttpPost]
      public async Task<IActionResult> AddNewAddress(CartAddressViewModel model, int clientId)
      {
          await GetStateAndDistricts();
          var userId = User.GetCurrentUserId();

          var result = await _orderService.CreateNewContactInfoByClient(model, userId);

          switch (result)
          {
              case CreateCartAddressResult.NotFound:
                  return Json(new { success = false, message = "Address not found." });

              case CreateCartAddressResult.AddressIsExists:
                  return Json(new { success = false, message = "This Address is registered Before" });

              case CreateCartAddressResult.Success:

                  return Json(new { success = true, message = "Address added successfully!", formData = model });

              default:
                  return Json(new { success = false, message = "An unexpected error occurred." });
          }
      }

after adding I want to update View of Checkout but just form 2.
this is my Ajax after adding new Address, How ever I get the correct data in Checkout method with update data, But it dose not show in its view ( on step form 2)

Code:
  $("#addNewAddressContainer").on("submit", "form", function (e) {
  e.preventDefault();

  var $form = $(this);
  var formData = $form.serialize();

  $.ajax({
      url: $form.attr("action"),
      type: $form.attr("method"),
      data: formData,
      success: function (response) {
          if (response.success) {
              ShowMessage(response.message); // From My ShowMessage Method
              $form.hide();

              $('html, body').animate({ scrollTop: 0 }, 'fast');
              $('#addressListContainer').empty();

              // Update the address list after successful submission
              $.ajax({
                  url: "/UserPanel/CheckOut", // Endpoint to fetch updated checkout page HTML
                  type: "GET",
                  success: function (updatedView) {
                      console.log('Successfully fetched updated checkout page.');
                      console.log(updatedView); // Log the received HTML for debugging

                      $("#addressListContainer").html(updatedView);
                  
                  },
                     
                  error: function () {
                      alert('Error occurred while loading address list.');
                  }
              });
          } else {
              ShowMessage(response.message);
          }
      },
      error: function () {
          ShowMessage('Error occurred while submitting the form.');
      }
  });

});

what is my wrong to return new view after update? I check it in log I receive correct data and for example 4 address, but in view I see just 3 address, it means does not add new address that I add it by enter code here

<p>this is my method to Get Cart:</p>
<pre><code> [HttpGet("/UserPanel/CheckOut")]
public async Task<IActionResult> CheckOut()
{


var text = await _siteService.GetSiteSettingForEdit();
var tax = text.Tax;

var userId = User.GetCurrentUserId();

// Get From Session
var cartItems = _orderService.GetFromSession();

// Update ClientId In ShowCart after Login
foreach (var item in cartItems)
{
if (item.ClientId == 0)
{
item.ClientId = userId;
}
}


// Get user addresses
var userAddresses = await _orderService.GetClientContactInfoById(userId);



// we check it in repo and create a list:
// List<CartAddressViewModel> cartAddresses = new List<CartAddressViewModel>();
//so we don't need to check if null, because in repo 100% create a list for it with object, but not null



var deliveryAndPaymentDetails = GetDeliveryAndPaymentDetailsFromSession();
//First get 0/0/1 then after run 2 script it will be change to the new date

// Create CartViewModel

var cartViewModel = new CartViewModel
{
Items = cartItems,
Tax = tax,
CartAddresses = userAddresses,
CartDeliveryDateViewModel = deliveryAndPaymentDetails

};


await GetStateAndDistricts();

return View(cartViewModel);
}
</code></pre>
<p>and I Add New Address in form 2 in my stepform :</p>
<pre><code> [HttpPost]
public async Task<IActionResult> AddNewAddress(CartAddressViewModel model, int clientId)
{
await GetStateAndDistricts();
var userId = User.GetCurrentUserId();

var result = await _orderService.CreateNewContactInfoByClient(model, userId);

switch (result)
{
case CreateCartAddressResult.NotFound:
return Json(new { success = false, message = "Address not found." });

case CreateCartAddressResult.AddressIsExists:
return Json(new { success = false, message = "This Address is registered Before" });

case CreateCartAddressResult.Success:

return Json(new { success = true, message = "Address added successfully!", formData = model });

default:
return Json(new { success = false, message = "An unexpected error occurred." });
}
}
</code></pre>
<p>after adding I want to update View of Checkout but just form 2.<br />
this is my Ajax after adding new Address, How ever I get the correct data in Checkout method with update data, But it dose not show in its view ( on step form 2)</p>
<pre><code> $("#addNewAddressContainer").on("submit", "form", function (e) {
e.preventDefault();

var $form = $(this);
var formData = $form.serialize();

$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: formData,
success: function (response) {
if (response.success) {
ShowMessage(response.message); // From My ShowMessage Method
$form.hide();

$('html, body').animate({ scrollTop: 0 }, 'fast');
$('#addressListContainer').empty();

// Update the address list after successful submission
$.ajax({
url: "/UserPanel/CheckOut", // Endpoint to fetch updated checkout page HTML
type: "GET",
success: function (updatedView) {
console.log('Successfully fetched updated checkout page.');
console.log(updatedView); // Log the received HTML for debugging

$("#addressListContainer").html(updatedView);

},

error: function () {
alert('Error occurred while loading address list.');
}
});
} else {
ShowMessage(response.message);
}
},
error: function () {
ShowMessage('Error occurred while submitting the form.');
}
});
</code></pre>
<p>});</p>
<p>what is my wrong to return new view after update? I check it in log I receive correct data and for example 4 address, but in view I see just 3 address, it means does not add new address that I add it by <code>enter code here</code></p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Ads by Eonads
Top