views:

205

answers:

1

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.TextBox("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

+1  A: 

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.

Darin Dimitrov
Thanks Darin. I've tried this but it still doesn't work. I've updated the question to state that I can see in the Text Visualiser that the Validation Summary does have the error message, it wont display on screen though. Is that a clue?
DaveDev
Try creating a new ASP.NET MVC project using the Visual Studio wizard and see if the sample I provided work for you.
Darin Dimitrov