ASP.NET MVC4 AJAX.BeginForm没有调用AjaxOptions OnSuccess

时间:2013-10-09 07:22:19

标签: javascript jquery ajax asp.net-mvc-4

我正在尝试在MVC4中使用Jquery Model Dialog,使用Razor对话框显示正常但AjaxOptions.OnSuccess javascript函数在我点击更新按钮后没有调用,但是它被重定向到http://<>:3738 /汽车/编辑/ 1?长度= 4我不知道它为什么会发生。

这是我的代码

CarController.cs

public class CarsController : Controller
{
    private ExpDb db = new ExpDb();

    //
    // GET: /Cars/

    public ActionResult Index()
    {
        return View(db.Cars.ToList());
    }



    //
    // GET: /Cars/Edit/5

    public ActionResult Edit(int id = 0)
    {
        CarModel carmodel = db.Cars.Find(id);
        if (carmodel == null)
        {
            return HttpNotFound();
        }
        return PartialView(carmodel);
    }

    //
    // POST: /Cars/Edit/5

    [HttpPost]
    public JsonResult  Edit(CarModel carmodel)
    {
        if (ModelState.IsValid)
        {

            db.Entry(carmodel).State = EntityState.Modified;
            db.SaveChanges();
            //return RedirectToAction("Index");
             return Json(JsonResponseFactory.SuccessResponse(carmodel),JsonRequestBehavior.DenyGet);
        }
      else {
            return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
        }
    }

Index.cshtml

@model IEnumerable<AjaxSamples.Models.CarModel>

@{
ViewBag.Title = "Index";
}
<div id="commonMessage"></div>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.ImageFileName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Description)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.ImageFileName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Description)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "editLink" }) |
        @Html.ActionLink("Details", "Details", new { id=item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.Id })

        <button id="opener">Open Dialog</button>
    </td>
  </tr>



 }

</table>

 <div id="updateDialog" title="Update Car"></div>
 <script type="text/javascript">
 var linkObj;
 $(function () {
    $(".editLink").button();

    $('#updateDialog').dialog({
        autoOpen: false,
        width: 400,
        resizable: false,
        modal: true,
        buttons: {
            "Update": function () {
                $("#update-message").html(''); //make sure there is nothing on the message before we continue                         
                $("#updateCarForm").submit();
            },
            "Cancel": function () {
                alert('sd');
                $(this).dialog("close");
            }
        }
    });

    $(".editLink").click(function () {
        //change the title of the dialog
        linkObj = $(this);
        var dialogDiv = $('#updateDialog');
        var viewUrl = linkObj.attr('href');
        $.get(viewUrl, function (data) {
            alert(data);
            dialogDiv.html(data);
            //validation
            var $form = $("#updateCarForm");
            // Unbind existing validation
            $form.unbind();
            $form.data("validator", null);
            // Check document for changes
            $.validator.unobtrusive.parse(document);
            // Re add validation with changes
            $form.validate($form.data("unobtrusiveValidation").options);
            //open dialog
            dialogDiv.dialog('open');
        });
        return false;
    });

});
function err(data) {
    alert(data);
}


 function updateSuccess(data) {
    alert(data);
}

Edit.cshtml

@model AjaxSamples.Models.CarModel

@{
ViewBag.Title = "Edit";
}

@using (Ajax.BeginForm("Edit", "Cars", new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace, 
        HttpMethod = "POST",
        OnSuccess = "updateSuccess"
    }, new { @id = "updateCarForm" }))
 {
 @Html.ValidationSummary(true)
<div id="update-message" class="error invisible"></div>
<fieldset>
    <legend>CarModel</legend>

    @Html.HiddenFor(model => model.Id)

    <div class="editor-label">
        @Html.LabelFor(model => model.ImageFileName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ImageFileName)
        @Html.ValidationMessageFor(model => model.ImageFileName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Description)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Description)
        @Html.ValidationMessageFor(model => model.Description)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

7 个答案:

答案 0 :(得分:17)

以下Jquery文件是必需的

jquery.unobtrusive-ajax.js

答案 1 :(得分:13)

我遇到的问题是我在$(document).ready()中声明了成功函数。我把它移到了外面并且有效。

即:

@using (Ajax.BeginForm("DialogTest", "Main", new AjaxOptions { HttpMethod = "Post", OnSuccess = "ajaxSuccess" }))
{
    <input type="button" id="info" value="Info" />
    <input type="button" id="confirm" value="Confirm" />
    <input type="button" id="wait" value="Wait" />
    <input type="button" id="ask" value="Ask" />
    <br /><br />
    <input type="submit" value="Submit" />
}



@section Scripts
{
    <script type="text/javascript">

        var ajaxSuccess = function () {
            alert('this is ajaxSuccess');
        }


        $(document).ready(function () {
            // do not declare ajaxSuccess here

            $('#mainForm').submit(function () {
                radarApp.InfoDialog("form submitted.");
                return false;
            });

// snip

答案 2 :(得分:1)

您需要在BeginForm调用中再添加一个参数:

Ajax.BeginForm("Edit","Cars", null, new AjaxOptions
               {
                   InsertionMode = InsertionMode.Replace,
                   HttpMethod = "POST",
                   OnSuccess = "updateSuccess"
               }, new { @id = ""updateCarForm })

null适用于RouteValueDictionary。 Here都是Ajax.BeginForm方法的重载。

答案 3 :(得分:1)

我有同样的问题。最初我在部分视图的头部区域有我的脚本......这导致了我的问题。

我把它移动到视图中的标题,它正在托管我的局部视图,一切正常。我的视图是一个托管在mvc应用程序中的引导页面,其布局设置为:“Layout = Nothing”。如果您的控制器操作正在加载视图,那么jquery.unobtrusive-ajax.js位置肯定存在问题......

答案 4 :(得分:1)

尝试:

@using(Ajax.BeginForm(“编辑”, 新{controller =“Cars”} ,新的AjaxOptions

答案 5 :(得分:0)

您可以直接在Script标签内使用Post方法来调用控制器方法,如:

@using (Html.BeginForm("Edit", "Cars", FormMethod.Post, new { id = "updateCarForm" }))
{
  .......Yourdata......
}

然后在Jquery

function PostForm(url) {
    $("#updateCarForm").valid();
    if ($("#updateCarForm").valid()) {
    $.post(url, $("#updateCarForm").serialize(), function (data) { updateSuccess(data); });
    }
}

答案 6 :(得分:0)

@ Alex的代码中存在语法错误,这应该有效:

Ajax.BeginForm("Edit","Cars", null, new AjaxOptions
           {
               InsertionMode = InsertionMode.Replace,
               HttpMethod = "Post",
               OnSuccess = "updateSuccess"
           }, new { id = "updateCarForm" })
{ /* Razor code */ }

具体而言,您应该关注Ajax.BeginForm()的{​​{3}}重载。