Question

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>
Was it helpful?

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.

OTHER TIPS

Thanks, I learnt the answer for this question from the reply of @Richard A. I did some modification to my code and it works fine.

I post it below, so might help some one.

ViewData from Controller

ViewData["Title"] = GetCustomerTitles(customer.Title);

View

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

The Idea is.. in Entity, the field name is "Title". After the form is posted, compiler check for a HTML element having the name "Title" and assign its value. If it is not present, it set the value of ModelState to false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top