I am using Asp.net MVC3 and trying to do a simple Ajax post to the server which returns a partial view and updates my list of items during a search.
@using (Ajax.BeginForm("PartialUpdate", "Listing"
, new AjaxOptions {
UpdateTargetId = "ListPartialDiv",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
}))
{
<!-- Search Boxes and buttons here -->
}
<div id = "ListPartialDiv">
@{
Html.RenderPartial("_ListPartial", Model);
}
</div>
The ajax successfully makes a call to the server and the server responds by sending a partial view. But the partial view always renders in a new page. I found out that this is because it doesn't know that it is an ajax call coming and so it renders a new page. I HAVE included the correct jquery-ubobtrusive-ajax.min.js scripts and added the key as follows according to This Question
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript">
My controller code is very simple:
if (Request.IsAjaxRequest())
return PartialView("_ListPartial", list);
return View("Index", list);
But Request.IsAjaxRequest() always returns false no matter what. I have also used fiddler and firebug according to This Question and don't see the X-Requested-With header but I can't really figure out what that means or how to change it. The only thing I can think of is that every other example I see uses an older version of jquery. Does that have anything to do with it? Thanks for any help.
你在jQuery之前包含了不引人注目的AJAX脚本,所以你的脚本都没有工作。
var controllerContext = MockRepository.GenerateMock<ControllerContext>();
controllerContext.Expect(c => c.HttpContext.Request["X-Requested-With"]).Return("XMLHttpRequest");
controller.ControllerContext = controllerContext;
You need to add the unobtrusive script after jquery script like this.
bundles.Add(new ScriptBundle("~/bundles/searchDemo").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
I stumbled on the similar situation where IsAjaxRequest() didn't work. I made sure Microsoft unobtrusive package is included. It still didn't help. Just upgraded to the latest version of unobtrusive library from package manager and it worked!
确保在其他jquery脚本文件之后引用jquery.unobtrusive.ajax.js / jquery.unobtrusive.ajax.min.js脚本文件,同时确保每页不要多次引用该文件,并且应该是分类
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.