代码之家  ›  专栏  ›  技术社区  ›  DaveDev

如何使用ASP.NET MVC进行验证-提交表单时模型状态无效

  •  1
  • DaveDev  · 技术社区  · 14 年前

    我试图在mvc中验证一个表单。

    我将自定义错误添加到模型状态,并在提交表单时将其作为无效错误获取。显示视图时,它不显示验证消息或验证摘要。有没有人能告诉我我做错了什么,或者如果有其他的方法可以证明我是正确的?

    编辑 这是ASP.NET MVC1。代码如下:

    以下是实体

    namespace DCS.DAL.Entities
    {
        public class Group : IDataErrorInfo
        {
            public int GroupId { get; set; }
    
            public string GroupName { get ; set; }
            public string AboutText { get; set; }
            public string LogoURL { get; set; }
            public string FriendlyURL { get; set; }
            public bool ExcludeFromFT { get; set; }
            public ContactInfo ContactInfo { get; set; }
    
            public string Error { get { return string.Empty;  } }
    
            public string this[string propName]
            {
                get
                {
                    if ((propName == "GroupName") && string.IsNullOrEmpty(GroupName))
                        return "Please enter Group Name";
                    return null;
                }
            }
    
    
        }
    }
    

    以下是视图

    <%= Html.ValidationSummary("Please correct following details") %>  
    
        <% using (Html.BeginForm()) {%>
    
        <div id="divError" Style="display:none;">
            errors 
            <%
                    foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState)
                    {
                        foreach (ModelError modelError in keyValuePair.Value.Errors)
                        {
                %> 
                             <% Response.Write(modelError.ErrorMessage); %>
                <%
                        }
                    }
                %>   
        </div>
    
            <fieldset>
    
                <table>
                    <tr>
                        <td>
                            <label for="GroupName">Group Name:</label>
                        </td>
                        <td>
                            <%= Html.TextBox("GroupName", Model.GroupName) %>
                            <%= Html.ValidationMessage("GroupName","group") %>
                        </td>
    

    foreach循环用于测试,它进入for循环,但不响应,不写入错误消息、验证摘要或验证消息。

    下面是控制器

    [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult EditGroup(Group group, FormCollection collection)
            {
                //Group group = new Group();
                bool success = false;
                try
                {
    
                        var contactInfo = new ContactInfo
                                              {
    
                                                  ContactName = collection["ContactName"],
                                                  Email = collection["Email"],
                                                  Fax = collection["Fax"],
                                                  HeadOfficeAddress = collection["HeadOfficeAddress"],
                                                  Freephone = collection["Freephone"],
                                                  Telephone = collection["Telephone"],
                                                  Website = collection["Website"]
                                              };
    
                    group.ContactInfo = contactInfo;
                    group.GroupName = collection["GroupName"];
                    if(string.IsNullOrEmpty(group.GroupName))
                    {
                        ModelState.AddModelError("GroupName", "Please enter group name");
    
                    }
    
                    if (!ModelState.IsValid)
                    {
                        success = groupRepository.InsertUpdateGroup(group);
                        return View(group);
                    }
    
                }
                catch
                {
    
                }
    
                //return Json(success);
                return View(group);
            }
    

    它确实进入了 if(!Modelstate.isvalid) 循环但不显示错误。

    编辑2 我可以在文本可视化程序中看到验证摘要确实有错误消息,但它不会显示在屏幕上。

    谢谢

    1 回复  |  直到 14 年前
        1
  •  2
  •   Darin Dimitrov    14 年前

    您可以用数据注释属性来修饰模型属性,使您能够执行一些验证逻辑。下面是一个简单的例子:

    模型:

    public class Group
    {
        [Required]
        public string GroupName { get; set; }
    }
    

    控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Group());
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(Group group)
        {
            // Remark: You don't need the FormCollection as argument to this action,
            // leave the default model binder do the job - it will also work
            // for the ContactInfo property as long as you name your text fields 
            // appropriately. For example Html.TextBox("ContactInfo.Email", Model.ContactInfo.Email)
            return View(group);
        }
    }
    

    观点:

    <% using (Html.BeginForm()) { %>
        <label for="GroupName">Group Name:</label>
        <%= Html.TextBox("GroupName", Model.GroupName) %>
        <%= Html.ValidationMessage("GroupName", "group") %>
        <input type="submit" value="Post" />
    <% } %>
    

    由您来决定数据注释是否足以满足您的情况,但请记住,如果您需要执行更高级的验证方案,您可以查看第三方框架,如 FluentValidation xVal .