将Ajax.BeginForm与ASP.NET MVC 3 Razor一起使用

JBe*_*ton 261 asp.net-mvc asp.net-mvc-3

是否存在Ajax.BeginForm在Asp.net MVC 3中使用的教程或代码示例,其中存在不显眼的验证和Ajax?

对于MVC 3来说,这是一个难以捉摸的话题,我似乎无法让我的表单正常工作.它将执行Ajax提交但忽略验证错误.

Dar*_*rov 427

例:

模型:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content("Thanks", "text/html");
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}
Run Code Online (Sandbox Code Playgroud)

这是一个更好的(在我看来)示例:

视图:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}
Run Code Online (Sandbox Code Playgroud)

index.js:

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

可以使用jQuery表单插件进一步增强.

  • 我同意将jquery用于Ajax.我认为绝大多数Asp.net MVC Ajax应用程序比使用内置的Ajax扩展使用jQuery. (41认同)
  • 我正在使用类似下面的内容,结果似乎是自己的页面而不只是替换div结果.你知道为什么吗? (6认同)
  • 是的,我同意使用纯jQuery for ajax,使用MVC ajax扩展意味着你需要不必要的学习其他规则和语法,最后使用jQuery.因此,即使我需要写更多,但最好以正确的方式做到这一点,再加上你获得更多的控制和灵活性. (3认同)
  • @ darin-dimitrov:当我尝试你的后一个例子时,我必须添加数据:$('form').serialize(),到ajax()调用.否则,没有表单数据传递,我的模型在服务器端无效.不知道有没有我忽略的东西? (3认同)
  • @DarinDimitrov如果BLL出错,您需要将模型发送回View并显示错误消息,因为强化层提供了更深入的数据验证并发现了问题.仅仅依靠客户端验证是不够的.你不能返回View(模型); 现在因为整个视图都在结果div中呈现...那是什么解决方法? (2认同)

Dro*_*ror 53

我认为所有答案都错过了一个关键点:

如果您使用Ajax表单以便它需要自己更新(而不是表单之外的另一个div),那么您需要将表单的包含div OUTSIDE.例如:

 <div id="target">
 @using (Ajax.BeginForm("MyAction", "MyController",
            new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "target"
            }))
 {
      <!-- whatever -->
 }
 </div>
Run Code Online (Sandbox Code Playgroud)

否则,您将像@David一样结束,其中结果显示在新页面中.

  • David的问题几乎总是因为不包含包含不显眼的ajax代码的jqueryval包.你要发布这种方法时要非常小心,否则你会得到一个帖子,然后你的表格会被替换掉.然后,您需要"MyAction"视图来管理其表单并重新指定其中的所有ajax选项. (7认同)

Jas*_*son 15

我最终得到了Darin的解决方案,但是首先犯了一些错误,这导致了类似David的问题(在Darin的解决方案下面的评论中),结果发布到了新的页面.

因为我必须在返回方法后对表单执行某些操作,所以我将其存储以供以后使用:

var form = $(this);
Run Code Online (Sandbox Code Playgroud)

但是,此变量没有在ajax调用中使用的"action"或"method"属性.

$(document).on("submit", "form", function (event) {
    var form = $(this);

    if (form.valid()) {
        $.ajax({
            url: form.action, // Not available to 'form' variable
            type: form.method,  // Not available to 'form' variable
            data: form.serialize(),
            success: function (html) {
                // Do something with the returned html.
            }
        });
    }

    event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

相反,你需要使用"this"变量:

$.ajax({
    url: this.action, 
    type: this.method,
    data: $(this).serialize(),
    success: function (html) {
        // Do something with the returned html.
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 那是因为你已经将表单变量设置为`jQuery`对象,表单作为选择器.`form [0]`会有属性.使用`$`为任何`jQuery`变量加前缀以更容易识别它们也是一种好习惯. (5认同)

che*_*eny 5

如果未执行数据验证,或者内容始终在新窗口中返回,请确保以下 3 行位于视图顶部:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)


ste*_*eno 5

Darin Dimitrov的解决方案对我有用,只有一个例外.当我提交带有(故意)验证错误的局部视图时,我最终在对话框中返回了重复的表单:

在此输入图像描述

要解决这个问题,我必须将Html.BeginForm包装在div中:

<div id="myForm">
    @using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
    {
        //form contents
    }
</div>
Run Code Online (Sandbox Code Playgroud)

提交表单后,我清除了成功函数中的div并输出了经过验证的表单:

    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#myForm').html('');
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)