MVC多个Ajax调用

时间:2015-02-20 15:57:18

标签: ajax asp.net-mvc unobtrusive-ajax

我在MVC应用程序中进行ajax调用时遇到问题。我已经尝试了两种不同的方法,可以让ajax actionlink加载一个部分,然后部分提交一个表单作为ajax调用,但我遇到了麻烦。

首次尝试

//将加载部分页面并将成功提交表单,但每次单击actionlink时它将加载另一个ajax脚本,因此当单击actionlink时,它将在第一次单击时调用控制器一次,两次第二,等...

Index.cshtml

@Ajax.ActionLink("Car 1, "EditCars", new { role = @Model.Car1}, new AjaxOptions
               {
                   HttpMethod = "GET",
                   InsertionMode = InsertionMode.Replace,
                   UpdateTargetId = "permissions",
               })
@Ajax.ActionLink(Car 2, "EditCars", new { role = @Model.Car2}, new AjaxOptions
               {
                   HttpMethod = "GET",
                   InsertionMode = InsertionMode.Replace,
                   UpdateTargetId = "permissions",
               })

<div id="permissions"></div>
// need to include this script to get the ajax action links to work
@Html.Script("~/Scripts/Main/jQuery.unobtrusive-ajax.js")

EditCars.cshtml

@using (Ajax.BeginForm("EditCars", "CarManagement", new AjaxOptions()))
{
     @Html.EditorFor(model => model.CarName)
     <input type="submit" />
}

 // need to include this script to get the ajax submit form to work
@Html.Script("~/Scripts/Main/jQuery.unobtrusive-ajax.js")

第二次尝试

//操作链接有效,但ajax提交表单没有。控制器返回新页面

Index.cshtml

@Ajax.ActionLink("Car 1, "EditCars", new { role = @Model.Car1}, new AjaxOptions
               {
                   HttpMethod = "GET",
                   InsertionMode = InsertionMode.Replace,
                   UpdateTargetId = "permissions",
               })
@Ajax.ActionLink(Car 2, "EditCars", new { role = @Model.Car2}, new AjaxOptions
               {
                   HttpMethod = "GET",
                   InsertionMode = InsertionMode.Replace,
                   UpdateTargetId = "permissions",
               })
@using (Ajax.BeginForm("EditCars", "CarManagement", new AjaxOptions()))
{
    <div id="permissions"></div>
    <input type="submit" />
}
// need to include this script to get ajax calls to work
@Html.Script("~/Scripts/Main/jQuery.unobtrusive-ajax.js")

EditCars.cshtml

@Html.EditorFor(model => model.CarName)

1 个答案:

答案 0 :(得分:0)

使用Nuget Manager获取最新版本的jQuery.unobtrusive-ajax.js:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax