简体   繁体   中英

How do I return JSON data from a partial view FormMethod.Get?

I have the following code that posts to my Search Json. The problem is the url redirects to the json search and displays the raw json data. I would like to return to a table in my partialView instead. Any thoughts on how I can achieve this?

<div>
@using (Html.BeginForm("Search", "Home", Formmethod.Get, new {id="search-form"})){
    ...
    <button id="search-btn">Search</button>
}
</div>
<div>
    <table id="search-results">...</table>
</div>

My home controller works fine but to make sure the picture is clear...

public JsonResult Search(/*variables*/)
{
    ...
    return Json(response, JsonRequestBehavior.AllowGet);
}

And I get redirected to "Search/(all my variables)

Your response data should be placed into a model, the model passed to a partial view, and the partial view returned from the controller.

public PartialViewResult Search(/*variables*/)
{
    ...
    YourModel model = new YourModel();
    // Populate model
    return PartialView("_YourPartialView", model);
}

If you want to refresh only the partial view, then you can call the controller action via ajax and call $('#yourDivContainingThePartialView').html(response) in the ajax callback:

$.ajax({
  url: urlToYourControllerAction,
  method: 'get', // or 'post', depending on whether your controller action has side effects
  success: function (response) {
      $('#yourDivContainingThePartialView').html(response);
  }
  // other ajax options here if you need them
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM