Search code examples
asp.net-mvc-3model-validation

Using DropDownLists to constrain and select Model values


I have a model for customer

public class Customer
{
    public virtual int CustomerID { get; set; }

    [Required]
    public virtual string CustomerName { get; set; }

    [Required]
    public virtual string Title { get; set; }

    [Required]
    public virtual string FirstName { get; set; }

    public virtual string LastName { get; set; }

    // Cont..
}

When I post the customer creation form to public ActionResult Create(Customer customer) which is an action in my CustomerController, it produce error against ModelState. For example... if my code is like below..

[HttpPost]
public ActionResult Create(Customer customer)
{
    customer.Title = "Mr"; // This is what I set for ensuring the field has value

    if (ModelState.IsValid)
    {
        // Code to save customer entity
    }
    // else..
}

In my MVC view it show the error in Customer Title

for instance, if I remove the if (ModelState.IsValid) portion from the code above, the customer entity is saved fine and I can see the record in database.

What might be the issue here?

EDIT :

passing Customer Titles as IEnumerable<SelectListItem>

ViewData["CustomerTitles"] = GetCustomerTitles();

Code in view

div class="editor-field">
    <%: Html.DropDownList("CustomerTitles")%>
    <br /><%: Html.ValidationMessageFor(model => model.Title) %>
</div>

Solution

  • Try this:

    <%: Html.DropDownList("Title", new SelectList(ViewData["CustomerTitles"]), Customer.Title.ToString()) %>
    

    This should hopefully pass the title in as a string, which is what your Model is asking for.