代码之家  ›  专栏  ›  技术社区  ›  Ogre Psalm33

ASP。NET MVC:TryUpdateModel中设置的验证消息未显示ValidationSummary

  •  2
  • Ogre Psalm33  · 技术社区  · 16 年前

    David Hayden's Blog ASP.Net MVC Tutorials

    <%@ 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... --%>
    

    对于一个看起来像这样的模型类:

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

    每当我输入一个无效的Age(因为Age被声明为int),例如“xxx”(非整数),视图

    以下是我的控制器代码中调用的操作:

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

    我错过了什么?

    1 回复  |  直到 12 年前
        1
  •  2
  •   Ogre Psalm33    16 年前

    ASP.NET MVC v1.0 source code 从微软,我发现,无论是偶然还是故意,都没有办法做我想做的事,至少在默认情况下是这样。显然,在调用UpdateModel或TryUpdateModel期间,如果整数验证(例如)失败,则不会在与ModelState关联的ModelError中为坏值显式设置ErrorMessage,而是设置Exception属性。根据MVC ValidationExtensions的代码,以下代码用于获取错误文本:

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

    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...
    }
    

    因此,如果模型错误。ErrorMessage属性为空(我在尝试将非整数值设置为声明的int时验证了这一点),MVC继续检查ModelState,我们已经发现它为null,因此任何Exception ModelError都会返回null。因此,在这一点上,我对这个问题的两个最佳解决方案是:

    1. 创建一个自定义验证扩展插件,当未设置ErrorMessage但设置了Exception时,该扩展插件会正确返回相应的消息。

    还有其他想法吗?