MVC 3 - 通过jquery和部分页面刷新提交表单以显示发布后的结果

7 jquery asp.net-mvc-3

我在MVC 3中有一个表单.目前我正在执行以下操作来发布表单.表单已发布,并且正在执行整页刷新以显示结果.

提交后,controll将发送状态成功或失败.而已.我只需要在div中显示基于返回状态的成功或失败消息.

有谁知道如何在MVC 3中执行此操作的高级步骤?

<div id="ShowResultHere"></div>

@using (Html.BeginForm("Update", "Test", FormMethod.Post, new { id="frmUpdate"}))
{
   //form fields
   <button type="submit" class="sprt bg_red bt_red h27">Update</button>
}

[HttpPost]
public ActionResult Update(TestModel model)
{
   return Json(new { s = "Success" });
}
Run Code Online (Sandbox Code Playgroud)

我希望Success在ShowResultHere div onsuccess回调中静默显示.

这可以在MVC 3中完成吗?

Dar*_*rov 19

您可以订阅submit表单事件并执行AJAX调用,如下所示:

$(function() {
    $('#frmUpdate').submit(function() {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
               // The AJAX call succeeded and the server returned a JSON 
               // with a property "s" => we can use this property
               // and set the html of the target div
               $('#ShowResultHere').html(result.s);
            }
        });
        // it is important to return false in order to 
        // cancel the default submission of the form
        // and perform the AJAX call
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)


Dav*_*veo 7

你也可以通过不写任何javascript来实现这一点.通过使用AJAX表单

<div id="ShowResultHere"></div>

@using (Ajax.BeginForm("Update", new AjaxOptions { UpdateTargetId = "ShowResultHere" }))
{

}
Run Code Online (Sandbox Code Playgroud)

并在你的控制器

[HttpPost]
public ActionResult Update(TestModel model)
{
    if(blah)
        return PartialView("Success")
    return PartialView("Failed")
}
Run Code Online (Sandbox Code Playgroud)

这样做意味着您必须创建两个视图.但意味着没有写javascript.