【问题标题】:ASP.NET MVC client valitation on ui-dialog?用户界面对话框上的 ASP.NET MVC 客户端验证?
【发布时间】:2012-06-29 11:49:17
【问题描述】:

剃须刀:

@Html.TextBoxFor(kod => kod.Name)
@Html.ValidationMessage("Name","Client Error Message")

控制器:

[HttpPost]
    public JsonResult JsonAddCustomer(Customers customer, string returnUrl)
    {
        if (customer.Name.Trim().Length == 0)
        {
            ModelState.AddModelError("Name", "Server Error Message");
        }

        //Eğer hata yoksa veri tabanına kayıt yapılıyor.
        if (ModelState.IsValid)
        {
            try
            {
                CusOpp.InsertCustomer(customer);
                return Json(new { success = true, redirect = returnUrl });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Error");
            }
        }

        return Json(new { errors = GetErrorsFromModelState() });
    }

我想写验证错误信息。我像上面那样做了,但@Html.ValidationMessage("Name","Client Error Message") 不起作用。事实上,我已经在期待它了。

我想显示如下语句的结果:@Html.ValidationMessageFor(m => m.name),但我不能使用它,因为我使用了实体数据模型。

我应该将[Required] 语句添加到数据模型类还是我这样做的任何方式。抱歉解释不好。

谢谢。

【问题讨论】:

    标签: json jquery-ui validation asp.net-mvc-4


    【解决方案1】:

    在这种情况下,您应该返回 PartialViews 而不是 JSON。只有在成功的情况下才能返回 JSON:

    [HttpPost]
    public ActionResult JsonAddCustomer(Customers customer, string returnUrl)
    {
        // Warning: the following line is something horrible => 
        // please decorate your view model with data annotations or use
        // FluentValidation.NET to validate it. 
        // Never write such code in a controller action.
        if (customer.Name.Trim().Length == 0)
        {
            ModelState.AddModelError("Name", "Server Error Message");
        }
    
        //Eğer hata yoksa veri tabanına kayıt yapılıyor.
        if (ModelState.IsValid)
        {
            try
            {
                CusOpp.InsertCustomer(customer);
                return Json(new { success = true, redirect = returnUrl });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Error");
            }
        }
    
        return PartialView(customer);
    }
    

    现在在您的 AJAX 请求的成功回调中,您可以测试 POST 操作是否成功:

    success: function(result) {
        if (result.redirect) {
            // we are in the success case => redirect
            window.location.href = result.redirect; 
        } else {
            // a partial view with the errors was returned => we must refresh the DOM
            $('#some_container').html(result);
    
            // TODO: if you are using unobtrusive client side validation here's 
            // the place to call the $.validator.unobtrusive.parse("form"); method in order 
            // to register the unobtrusive validators on the newly added contents
        }
    }
    

    这里有一个similar post,您也可以阅读一下。

    【讨论】:

    • 我的模型中有很多列要验证。所以我不想写“if 语句”进行验证。我有任何解决方案,例如 public class FeedBack { [Required] [Display(Name = "Feedback")] public string Feedback { get;放; } }
    • 是的,确切地说,你应该在你的视图模型上使用数据注解,并用必要的属性来装饰相应的属性,而不是在你的控制器动作中编写那些 if 条件。
    • 我使用实体模型。我该怎么做?
    • 哦,不,这是一个非常错误的方法。您永远不应该将域实体传递给视图。您应该使用视图模型,它们是您专门为满足视图要求而设计的类。
    • 请注意,我最近开始使用 AutoMapper 在我的数据模型和我的视图模型之间进行转换。如果 OP 想知道转化,我认为值得一提。
    【解决方案2】:

    在模型上带有必需注释的想法是一个好方法。您可以在必需注释上设置错误消息。

    [Required(ErrorMessage = "Please enter a name")]
    

    并在你的行动中删除你的 if..this:

    if (customer.Name.Trim().Length == 0)
            {
                ModelState.AddModelError("Name", "Server Error Message");
            }
    

    ModelState.IsValid 将在客户端和服务器端为您完成这项工作。

    并在您的视图中使用您的 @Html.ValidationMessageFor(m => m.name)

    【讨论】:

    • 这是我使用实体数据模型的问题。我在哪里写 [Required(ErrorMessage = "Please enter a name")] ??
    • 确定一个视图模型是关键:stackoverflow.com/questions/7735635/…
    • 我自己不写课程。有来自实体数据模型。我应该写我的模型吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多