Home > Software engineering >  How to bind a model to URL Action in success ajax call section?
How to bind a model to URL Action in success ajax call section?

Time:11-07

I'm working with ASP.NET Core. I want to add a model to URL. This model comes from controller to success section of an ajax call. View's code:

<form>
  <div asp-validation-summary="ModelOnly" ></div>
       /// Some Input Tag
  <div >
     <button type="button" onclick="FilterOrder()"> Filter </button>
  </div>
</form>
<script>
    function FilterOrder() {
        var _url = '@Url.Action("Filter", "Controller")';
        $.ajax({
            url: _url,
            type: "POST",
            data: {
                  // Some data to send as a model
            },
            success: function (response) {
                console.log("Success");
                 window.location.href = '@Url.Action("ShowList", "Controller")/'   response; //has error 500
            },

        });
    }
</script>

Controller's code:

[HttpPost]
public IActionResult Filter(MyViewModel viewModel)
{
   if (ModelState.IsValid)
   {
      var list= FilterLists(viewModel);
      return Ok(list);
   }
   else
   {
      return View(viewModel);
   }
}
[HttpPost]
public IActionResult ShowList(List<Model> list)
{
   return View(list);
}

How to change my code to work correctly?

CodePudding user response:

window.location.href=xx can't send a HttpPost request, So you can't use this method to load modal. One of methods is send another post ajax in success function then show the return html in the page, You can refer to this simple demo:

<script>
    function FilterOrder() {
        var _url = '@Url.Action("Filter", "Controller")';
        $.ajax({
            url: _url,
            type: "POST",
            data: {
                  // Some data to send as a model
            },
            success: function (response) {
                //send another ajax post request.
                $.ajax({
                    url: /Controller/ShowList,
                    type: "POST",                        
                    data: xxxx,
                    success: function (res) {
                       
                        //define a div to show the return html
                        document.getElementById("xxx").innerHTML = res,

                       //close the modal
                       $('#modalId').modal('hide')
                    },   
                });
            }

        });
    }
</script>
  • Related