我正在使用vs2010。下面的程序应该从数据库中获取数据并在不刷新页面的情况下进行渲染。但是当我输入一些名称并单击搜索按钮时,下面的程序总是刷新页面。
Index.cshtml
@model IEnumerable<OdeToFood.Models.RestaurentListViewModel>
@{
ViewBag.Title = "Home Page";
}
<form method="get" action="@Url.Action("Index")" data-otf-ajax="true" data-otf-target="#restaurentList">
<input type="text" name="searchTerm" />
<input type="submit" value="Search"/>
</form>
@Html.Partial("_Restaurents",Model)
当程序运行时,控件永远不会进入 if(Request.IsAjaxRequest())
Homecontroller.cs
public ActionResult Index( string searchTerm=null)
{
var model = _db.Restaurent.OrderByDescending(r => r.RestaurentReview.Average(review => review.Rating))
.Where(r=>searchTerm==null || r.Name.StartsWith(searchTerm))
.Take(10)
.Select(r => new RestaurentListViewModel
{
id = r.id,
Name = r.Name,
City = r.City,
Country = r.Country,
CountOfReviews = r.RestaurentReview.Count()
});
if (Request.IsAjaxRequest()) {//control never comes inside the if
return PartialView("_Restaurents",model);
}
return View(model);
}
otf.js
$(function () {
var AjaxFormSubmit = function () {
alert("hai ajax");
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-otf-target"));
$target.replace(data);
});
return false;
};
$("form[data-otf-ajax='true']").submit(AjaxFormSubmit);
});
BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/otf").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*",
"~/Scripts/otf.js"
));
但是,如果我提供以下代码,程序正在运行而不刷新页面。
@using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "restaurentList"
}))
{
<input type="text" name="searchTerm" />
<input type="submit" value="Search"/>
}
那么我的第一个代码有什么问题..请帮助我