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

时间:2010-04-28 10:36:48

标签: asp.net-mvc validation

我正在尝试验证MVC中的表单。

我向模型状态添加自定义错误,并在提交表单时将其设置为无效。显示视图时,它不显示验证消息或验证摘要。任何人都可以让我知道我做错了什么,或者如果有任何其他验证方法,请指出我正确的方向?

编辑这是ASP.NET MVC 1.这是代码:

以下是实体

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 我可以在Text Visualiser中看到验证摘要确实有错误消息,但它不会显示在屏幕上。

由于

1 个答案:

答案 0 :(得分:2)

您可以使用数据注释属性修饰模型属性,从而允许您执行一些验证逻辑。这是一个简化的例子:

型号:

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和{{ 3}}