Reputation: 1609
I have the following controller and view:
SearchController.cs:
public class SearchController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SearchResults()
{
int rnd = new Random().Next(100);
var model = new List<SearchResultModel>
{
new SearchResultModel { Id=rnd, FirstName="Peter" + rnd, Surname="Pan" },
new SearchResultModel { Id=rnd+1, FirstName="Jane", Surname="Doe"+rnd }
};
return PartialView("SearchResults", model);
}
}
Index.cshtml:
@model WebApplication1.Models.SearchCriterionModel
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function (evt) {
evt.preventDefault();
$('#placeholder').load("/Search/SearchResults");
})
});
</script>
<button id="btnSearch">Search</button>
<div id="placeholder"></div>
I just figured out that the template I used for the view (the standard Edit template) inserted a Html.BeginForm
which somehow didn't let me fill a partial view into my div
. So I removed the clutter and tried 'from scratch' and look - it worked. I can now successfully load the partial view SearchResults
into the div
with id = placeholder
.
But: this only works once. That is, on the first button click, the code-behind method SearchResults()
is called and the div
is filled with the first set of 'randomized' data. Clicking more than once does enter the client-side click method, but doesn't go into my SearchResults()
method anymore, so I guess no post-back is happening!?
Why is that so? And how can I 'fix' this, that is, learn how to do it right and get new data everytime I press the button?
Upvotes: 1
Views: 1042
Reputation: 1609
For completion's sake, this is how I ended up doing it.
First, I used a form because I wanted to pass parameters to the action method in the controller, similar to this:
@using(Html.BeginForm())
{
.
.
some input elements
.
.
<input type="submit" value="Search" />
}
Then I used the following script. Note that for this to work the action method now has to take an instance of the ViewModel as parameter as well.
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function () {
var model = $(this).serialize();
$.ajax({
url: '@Url.Action("SearchResults", "Search")',
data: model,
cache: false,
dataType: "html",
success: function (response) {
$("#placeholder").html(response);
}
});
return false;
})
});
</script>
Upvotes: 1
Reputation: 1022
My MVC is a bit rusty, but you could try adding a random number to the URL so the browser won't get it from cache. Not sure if the controller method will ignore the 'r' parameter or not.
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function (evt) {
evt.preventDefault();
var random = getRandomNumber(); //TODO: implement
$('#placeholder').load("/Search/SearchResults?r=" + random);
})
});
</script>
Upvotes: 1