rajeemcariazo
rajeemcariazo

Reputation: 2524

ModelState is always invalid when Dropdownlist is on ViewModel

I have this ViewModel:

public class CreateUserModel {
  public int StateId { get; set; }
  public IEnumerable<SelectListItem> States { get; set; }
}

Here is my View:

@Html.DropDownListFor(model => model.StateId, Model.States, "--select state--")

Here is my Controller:

public ActionResult Create()
{
    var model= new CreateUserModel();
    model.States = new SelectList(_context.States.ToList(), "Id", "Name");
    return View(model);
}

[HttpPost]
public ActionResult Create(CreateUserModel model)
{
    if (ModelState.IsValid)
    {
        _context.Users.Add(new User()
        {
          StateId = model.StateId
        });
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    else
    {
        return View(model);
    }
}

This error makes ModelState invalid:

System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types.


Edited to include my complete view:

@model AgreementsAndAwardsDB.ViewModels.CreateUserModel

    <!DOCTYPE html>
    <html>
    <head>

        <script src="~/Scripts/jquery-1.8.3.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
        <script src="~/Scripts/jquery.validate.min.js"></script>
       </head>
    <body class="createPage">
        @using (Html.BeginForm("Create", "Accounts", Model, FormMethod.Post))
        {
            @Html.DropDownList("StateId", Model.States)
            <input type="submit" />
        }
    </body>
    </html>

Upvotes: 1

Views: 1165

Answers (1)

JLe
JLe

Reputation: 2904

You are passing your model as route values to the form action using this line:

@using (Html.BeginForm("Create", "Accounts", Model, FormMethod.Post))

Since the IEnumerable<SelectListItem> States can't be parsed in a good way for querystrings, the form action will be Accounts/Create?StateId=0&States=System.Web.Mvc.SelectList and the model binder will try to bind the string "System.Web.Mvc.SelectList" to an IEnumerable<>, which is why your code doesn't work.

You would probably be OK with just

@using (Html.BeginForm())

, but if you want to specify action, controller and method go for

@using (Html.BeginForm("Create", "Accounts", FormMethod.Post))

Upvotes: 3

Related Questions