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