开发者

How to Validate with ASP.NET MVC - Model State is Invalid When Form Submitted

I am trying to validate a form in MVC.

I add custom errors to model state and get it as invalid when form is submitted. When the view is displayed it doesn’t show validation messages nor validation summary. Can anyone please let me know what am I doing wrong or point me in the right direction if there is any other way of validating?

Edit This is ASP.NET MVC 1. Here's the code:

Following is the entity

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


    }
}

Following is the view

<%= 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.Te开发者_如何学运维xtBox("GroupName", Model.GroupName) %>
                        <%= Html.ValidationMessage("GroupName","group") %>
                    </td>

Foreach loop is for testing, it does gets into the for loop but doesn’t response.write error message nor validation summary nor validation message.

Following is the controller

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

It does go into the if(!Modelstate.isvalid) loop but it doesn’t display error.

Edit 2 I can see in the Text Visualiser that the Validation Summary does have the error message, it wont display on screen though.

Thanks


You could decorate your model properties with data annotation attributes allowing you to perform some validation logic. Here's a simplified example:

Model:

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

Controller:

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

View:

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

It's up to you to decide whether Data Annotations are sufficient for your case, but bear in mind that if you need to perform more advanced validation scenarios you might take a look at third party frameworks like FluentValidation and xVal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜