MVC validation error with strongly typed view

Posted by Remnant on Stack Overflow See other posts from Stack Overflow or by Remnant
Published on 2010-06-03T11:21:46Z Indexed on 2010/06/03 11:24 UTC
Read the original article Hit count: 255

Filed under:
|
|

I have a simple form that I would like to validate on form submission. Note I have stripped out the html for ease of viewing

<%=Html.TextBox("LastName", "")%> //Lastname entry
<%=Html.ValidationMessage("LastName")%>

<%=Html.TextBox("FirstName", "")%>//Firstname entry
<%=Html.ValidationMessage("FirstName")%>

<%=Html.DropDownList("JobRole", Model.JobRoleList)%> //Dropdownlist of job roles

<% foreach (var record in Model.Courses) // Checkboxes of different courses for user to select
   { %>
       <li><label><input type="checkbox" name="Courses" value="<%=record.CourseName%>" /><%= record.CourseName%></label></li>
   <% } %>  

On submission of this form I would like to check that both FirstName and LastName are populated (i.e. non-zero length).

In my controller I have:

public ActionResult Submit(string FirstName, string LastName)
{
   if (FirstName.Trim().Length == 0)
   ModelState.AddModelError("FirstName", "You must enter a first name");

   if (LastName.Trim().Length == 0)
   ModelState.AddModelError("LastName", "You must enter a first name");

   if (ModelState.IsValid)
    {
      //Update database + redirect to action
    }

   return View(); //If ModelState not valid, return to View and show error messages
}

Unfortunately, this code logic produces an error that states that no objects are found for JobRole and Courses.

If I remove the dropdownlist and checkboxes then all works fine.

The issue appears to be that when I return the View the view is expecting objects for the dropwdownlist and checkboxes (which is sensible as that is what is in my View code)

How can I overcome this problem?

Things I have considered:

  1. In my controller I could create a JobRoleList object and Course object to pass to the View so that it has the objects to render. The issue with this is that it will overwrite any dropdownlist / checkbox selections that the user has already made.
  2. In the parameters of my controller method Submit I could aslo capture the JobRoleList object and Course object to pass back to the View. Again, not sure this would capture any items the user has already selected.

I have done much googling and reading but I cannot find a good answer. When I look at examples in books or online (e.g. Nerddinner) all the validation examples involve simple forms with TextBox inputs and don't seems to show instances with multiple checkboxes and dropdownlists.

Have I missed something obvious here? What would be best practice in this situation?

Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc