views:

83

answers:

2

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

A: 

In simple MVC validation your supposed to pass the strongly typed object in other words your views model.

Example:

public ActionResult Update(Employees employee)
{

if (employee.Name.Trim().Length == 0)
        ModelState.AddModelError("Name", "Name is required.");

// ETC....

}
JeremySpouken
+1  A: 

The best practice would be to accept a view-specific model. You could have a shared model that has both the properties that are needed to render the page and the properties required on post or separate models for rendering and accepting the post parameters. I usually go with a shared model as that means I can simply return the model I've received, suitably re-populated with any data needed to generate menus (such as JobList and Courses). Often I will have a method that takes a model of this type and returns a view with the menu properties populated.

   public ActionResult JobsView( JobsViewModel model )
   {
        model.JobList = db.Jobs.Select( j => new SelectListItem 
                                             {
                                                  Text = j.Name,
                                                  Value = j.ID.ToString()
                                             });
        ...
        return View( model );
   }

Then call this method from any of my actions that require a view with this type of model, to ensure that the model has the proper menu data.

   // on error, return the view
   return JobsView( model );

When using a model, you can also use DataAnnotations to decorate your model properties and let the model binder do validation for you, as well as enable client-side validation based on the model. Any validation not supported by the existing attributes can be implemented by creating your own attributes or done within the controller action.

  public class JobsViewModel
  {
       [Required]
       public string FirstName { get; set; }

       [Required]
       public string LastName { get; set; }

       public int JobRole { get; set; }

       [ScaffoldColumn(false)]
       public IEnumerable<SelectListItem> JobRoleList { get; set; }

       ...
  }

  public ActionResult Submit( JobsViewModel model )
  {
       if (ModelState.IsValid)
       {
           ... convert model to entity and save to DB...
       }

       return JobsView( model );
  }

Then enable validation in your HTML

...
<script type="text/javascript" src="<%= Url.Content( "~/scripts/MicrosoftMvcValidation.js" ) %>"></script>

<% Html.EnableClientValidation(); %>

... begin form...

<%=Html.TextBoxFor( m=> m.LastName )%>
<%=Html.ValidationMessageFor( m => m.LastName )%>

<%=Html.TextBoxFor( m=> m.FirstName )%>
<%=Html.ValidationMessageFor( m => m.FirstName )%>

<%=Html.DropDownListFor( m=> m.JobRole, Model.JobRoleList)%>

<% 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>
   <% } %>  
tvanfosson
Thanks. I have adopted your methodology and things are working fine now. It does feel like my ViewModel is a little bloated with data that I may or may not use but for what I am doing I don't anticipate it would cause me any issues. Thanks for taking time to advise me.
Remnant
@Remnant- As I said, you could have separate models (using subclassing if appropriate) for display/post, but then you'd need a way to transform between them when you have an error instead of merely populating the missing bits.
tvanfosson