Model设置验证信息不showning的ValidationS

Model设置验证信息不showning的ValidationS

本文介绍了ASP.NET MVC:在TryUpdateModel设置验证信息不showning的ValidationSummary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直努力遵循在网络上验证教程和例子,如大卫·海登的博客和官方,但我不能让下面的code来显示实际验证错误。如果我有一个看起来像这样一个观点:

I've been trying to follow the validation tutorials and examples on the web, such as from David Hayden's Blog and the official ASP.Net MVC Tutorials, but I can't get the below code to display the actual validation errors. If I have a view that looks something like this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Parent>" %>

<%-- ... content stuff ... --%>

<%= Html.ValidationSummary("Edit was unsuccessful. Correct errors and retry.") %>
<% using (Html.BeginForm()) {%>

<%-- ... "Parent" editor form stuff... --%>

        <p>
            <label for="Age">Age:</label>
            <%= Html.TextBox("Age", Model.Age)%>
            <%= Html.ValidationMessage("Age", "*")%>
        </p>

<%-- etc... --%>

有关,看起来像这样一个模型类:

For a model class that looks like this:

public class Parent
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public int Age { get; set; }
    public int Id { get; set; }
}

每当我进入一个无效的时代(因为年龄被声明为int),如XXX(非整数),视图的确实的正确显示消息编辑是不成功的,正确的错误重试,在屏幕的顶部,以及突出时代文本框,并把它旁边的红色星号,指示错误。然而,将显示在ValidationSummary没有错误消息的列表。当我做我自己的验证(例如:下面姓氏),该消息显示正确,但TryUpdateModel的内置的验证似乎并没有显示消息时,现场有一个非法值。

Whenever I enter an invalid Age (since Age is declared as an int), such as "xxx" (non-integer), the view does correctly display the message "Edit was unsuccessful. Correct errors and retry" at the top of the screen, as well as highlighting the Age text box and put a red asterisk next to it, indicating the error. However, no list of error messages is displayed with the ValidationSummary. When I do my own validation (e.g.: for LastName below), the message displays correctly, but the built-in validation of TryUpdateModel does not seem to display a message when a field has an illegal value.

下面是动作在我的控制器code调用:

Here is the action invoked in my controller code:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult EditParent(int id, FormCollection collection)
    {
        // Get an updated version of the Parent from the repository:
        Parent currentParent = theParentService.Read(id);

        // Exclude database "Id" from the update:
        TryUpdateModel(currentParent, null, null, new string[]{"Id"});
        if (String.IsNullOrEmpty(currentParent.LastName))
            ModelState.AddModelError("LastName", "Last name can't be empty.");
        if (!ModelState.IsValid)
            return View(currentParent);

        theParentService.Update(currentParent);
        return View(currentParent);
    }

我错过了什么?

推荐答案

我下载了,看着和发现,无论是偶然的还是,没有办法做我想做的事,至少是默认。显然期间的UpdateModel或TryUpdateModel呼叫,如果一个整数(例如)的验证失败,一个的ErrorMessage没有明确与ModelState中的坏值相关的ModelError设置,而是异常属性设置。据来自MVC ValidationExtensions的code,以下code用于获取错误文本:

I downloaded and looked at the ASP.NET MVC v1.0 source code from Microsoft, and discovered that, either by accident or by design, there isn't a way to do what I want to do, at least by default. Apparently during a call to UpdateModel or TryUpdateModel, if validation of an integer (for example) fails, an ErrorMessage is not explicitly set in the ModelError associated with the ModelState for the bad value, but instead the Exception property is set. According to the code from the MVC ValidationExtensions, the following code is used to fetch the error text:

string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);

注意的ModelState中的空参数传递。该GetUserErrorMEssageOrDefault方法则是这样开始的:

Notice the null parameter for the modelState is passed. The GetUserErrorMEssageOrDefault method then begins like this:

private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) {
    if (!String.IsNullOrEmpty(error.ErrorMessage)) {
        return error.ErrorMessage;
    }
    if (modelState == null) {
        return null;
    }

    // Remaining code to fetch displayed string value...
}

所以,如果ModelError.ErrorMessage属性为空(我证实,这是试图将非整数值设置为一个申报INT时),MVC接着检查ModelState中,我们已发现为空,因此返回null任何异常ModelError。所以,在这一点上,我最好的2工作围绕思想这个问题是:

So, if the ModelError.ErrorMessage property is empty (which I verified that it is when trying to set a non-integer value to a declared int), MVC goes on to check the ModelState, which we already discovered is null, thus null is returned for any Exception ModelError. So, at this point, my 2 best work-around ideas to this issue are:


  1. 创建一个自定义的验证扩展正确返回时,未设置的ErrorMessage适当的消息,但例外设置。

  2. 创建被称为控制器如果ModelState.IsValid返回false一个pre-处理功能。在pre-处理功能将查找其中的ErrorMessage没有设置在ModelState中值,但唯一的例外是设置,然后导出使用ModelState.Value.AttemptedValue相应的消息。

任何其他的想法?

这篇关于ASP.NET MVC:在TryUpdateModel设置验证信息不showning的ValidationSummary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:01