0

剃刀:

@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]语句添加到数据模型类还是我这样做的任何方式。抱歉解释不好。

谢谢。

4

2 回答 2

2

在这种情况下,您应该返回 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
    }
}

这是一篇类似的文章,您也可以阅读。

于 2012-06-29T12:02:11.723 回答
0

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

[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)

于 2012-06-29T12:09:20.587 回答