jquery客户端验证仅适用于某些字段(在必填字段不起作用)

时间:2011-10-16 04:42:52

标签: asp.net-mvc-3 validation jquery-dialog

我正在mvc3中实现客户端验证。 我通过jquery对话框显示我的表单,并通过ajax post提交 我不确定是否有必要,但我在我的模型中创建了一个部分类来自定义验证:

[MetadataType(typeof (FoodMetaData))]
public partial class FOOD
{
    [Bind(Exclude="FoodID")]
    public class FoodMetaData
    {
        [ScaffoldColumn(false)]
        public object FoodID { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter a name")]
        public object FoodName { get; set; }

        [Range(1, 200, ErrorMessage = "Please enter a valid amount")]
        public object FoodAmount { get; set; }

        public object StorageDate { get; set; }

        public object ExpiryDate { get; set; }

目前,如果输入字符串或超出范围的数字,我只会在金额字段中显示验证。但是,如果我清空名称字段,则不会发生任何事情。

这是我第一次尝试客户端验证,不知道发生了什么。有人可以给我一些建议吗?

感谢任何帮助,谢谢...

2 个答案:

答案 0 :(得分:2)

以下是如何使用jQuery对话框实现部分表单的示例。

一如既往地从视图模型开始:

public class MyViewModel
{
    [Required]
    public string SomeProperty { get; set; }
}

然后是控制器:

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

    public ActionResult Edit()
    {
        return PartialView(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Edit(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return PartialView(model);
        }
        // TODO: validation passed => process the model and return a JSON success
        return Json(true);
    }
}

然后是~/Views/Home/Index.cshtml视图,其中只包含对话框的链接:

@Html.ActionLink("click me for dialog", "edit", null, new { id = "showDialog" })
<div id="dialog"></div>

~/Views/Home/Edit.cstml部分将包含我们希望在对话框中显示的表单:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.SomeProperty)
    @Html.EditorFor(x => x.SomeProperty)
    @Html.ValidationMessageFor(x => x.SomeProperty)
    <button type="submit">Save</button>
}

现在剩下的就是连线。所以我们导入必要的脚本:

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<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>

然后编写我们自己的对话框:

$(function () {
    $('#showDialog').click(function () {
        $('#dialog').dialog().load(this.href, function (result) {
            ajaxify(this);
        });
        return false;
    });
});

function ajaxify(dialog) {
    // we need to parse client validation rules
    // because the form was injected into the DOM later as
    // part of the dialog. It was not present initially
    // See here for more info: http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
    $.validator.unobtrusive.parse($(dialog));

    // AJAXify the form
    $('form', dialog).submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result === true) {
                    // The controller action returned a JSON result
                    // inidicating the success
                    alert('thank you for submitting');
                    $(dialog).dialog('close');
                } else {
                    // there was a validation error => we refresh the dialog
                    // and reajaxify it as we have now modified the DOM
                    dialog.html(result);
                    ajaxify(dialog);
                }
            }
        });
        return false;
    });
}

现在,您可以使用任何编辑器模板和验证规则将其调整到您想要的任何视图模型。

答案 1 :(得分:2)

我刚刚发现jquery客户端验证仅在我通过此处的示例提交第一个表单后触发:http://weblogs.asp.net/imranbaloch/archive/2011/04/30/eagerly-performing-asp-net-mvc-3-unobtrusive-client-side-validation.aspx

一个伟大的人!通过编辑jquery.validate.unobtrusive(.min).js文件有助于解决我的奇怪问题:

   options: {  // options structure passed to jQuery Validate's validate() method
                errorClass: "input-validation-error",
                errorElement: "span",
                errorPlacement: $.proxy(onError, form),
                invalidHandler: $.proxy(onErrors, form),
                messages: {},
                rules: {},
                success: $.proxy(onSuccess, form),
                onfocusout: function (element) { $(element).valid(); }
            }

感谢您的帮助!