Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 830003
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T03:58:21+00:00 2026-05-15T03:58:21+00:00

I have a simple form that I would like to validate on form submission.

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T03:58:22+00:00Added an answer on May 15, 2026 at 3:58 am

    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>
       <% } %>  
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to have a custom snippet of html form code that takes
I have a simple search form that looks something like: app/views/search/index.html.erb <%= form_for @search,
There are some HTML based games (ie bootleggers.us) that have a simple login form
I have a site that has a simple HTML button in a form. All
I have a simple form with some plain html input like bellow using ASP.NET
I have a simple HTML Form that allows the user to enter some text
I have a simple .NET 2.0 windows form app that runs off of a
I'm writing a simple app that's going to have a tiny form sitting in
I am creating a simple form. I would like to use embedded javascript to
this is a simple question. I have a form that is being validated using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.