$.support
( http://api.jquery.com/jQuery.support/を参照) を使用すると、AJAX が有効になっているかどうかを確認できます。
$.support.ajax
AJAX が有効かどうかがわかったら、スマート検索ボタンを作成できます。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
}
コントローラ アクションが検索を実行するようにセットアップされたので、2 つの異なるビューが必要です。
- 検索結果の HTML をレンダリングする部分ビュー (「_Results」と呼ばれます)
- ブラウザが AJAX をサポートしていない (「検索」と呼ばれる) 場合に部分ビューをラップする完全なビュー
これで、「検索」ページは次のようになります。
@model MySearchResultsModel
<h2>Search Results</h2>
@Html.Partial("_Results",model)
「_Results」には生の HTMl が含まれるか、MVC WebGrid を使用します。
@model MySearchResultsModel
<ul>
@foreach(var result in MySearchResultsModel.Results)
{
<li>@result.SomeProperty</li>
}
</ul>
では、すべてを機能させるにはどうすればよいでしょうか。ページに「searchResults」という ID を持つ div があるとします。
<div id="searchResults"></div>
また、検索用のフォームが必要になります。
<form action="@Url.Action("Search")" id="searchForm">
<input type="text" name="q" value=""/>
<input type="submit" value="Search"/>
</form>
また、フォームの送信をキャプチャするには、いくつかの JS が必要です。
$(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');
}
});
}
});
});