問題描述
使用 Jquery 的 mvc3 搜索結果 (mvc3 search results with Jquery)
I am working on a Asp.Net MVC3 webapplication.I have a textbox and a button. I use a MVC WebGrid to display data in UI based on the search string. I am trying to pull mvc webgrid with out page postback using jquery. I need some help in Jquery code to populate data with out post back.
What I am doing right now is jquery on button click or on selected item I am taking selected id an redirecting to page again as below.
select: function (event, ui) {
$.ajax({ url: 'ControllerName',
type: 'POST',
data: { id: ui.item.id
},
async: false,
success: function (result) {
window.location.replace("ControllerName" + '?id=' + ui.item.id);
}
});
參考解法
方法 1:
With the use of the $.support
(see http://api.jquery.com/jQuery.support/) you can check to see if AJAX is enabled or not:
$.support.ajax
Once we know if AJAX is enabled or not we can build a smart search button. Lets setup your Controller/Actions in MVC:
public ActionResult Search(string q)
{
//TODO: Some logic to perform a search
MySearchResultsModel results = new MySearchResultsModel(); //Populate results with some model of data
if (Request.IsAjaxRequest())
return PartialView("_Results", results); //partial view w/ results
else
return View("Search",results); //Returns a full page
}
Now that our controller action is setup to perform a search we need two different views:
- A partial view that will render out the HTML of your search results (called "_Results")
- A full view that will wrap the partial view incase the browser doesn't (called Search") support AJAX
Now, the "Search" page would look something like:
@model MySearchResultsModel
<h2>Search Results</h2>
@Html.Partial("_Results",model)
The "_Results" would contain either raw HTMl or make use of your MVC WebGrid:
@model MySearchResultsModel
<ul>
@foreach(var result in MySearchResultsModel.Results)
{
<li>@result.SomeProperty</li>
}
</ul>
Now, how to make it all work? Lets say your page has a div on it with an id of "searchResults":
<div id="searchResults"></div>
And you'll need a form for the search:
<form action="@Url.Action("Search")" id="searchForm">
<input type="text" name="q" value=""/>
<input type="submit" value="Search"/>
</form>
And you'll need some JS to capture the form submit
$(function(){
$('#searchForm').submit(function(e){
if($.support.ajax) //Is AJAX enalbed?
{
e.preventDefault(); //prevent the form from submitting
//Send the request via AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'), //Read the action from the FORM url OR you could use @Url.Action('Search')
data: $(this).serialize(), //The forms data
success: function (response) {
$('#searchResults').html(response); //This sets the DIV's contents to the AJAX response
},
error: function () {
alert('An error occured while performing your search');
}
});
}
});
});