开发者

MVC3 Model Binding to a Select List

开发者 https://www.devze.com 2023-03-02 02:14 出处:网络
I\'ve been using the MVCScaffolding feature to create a CRUD UI for my data stored using EF4.1 It works well for basic scenarios and binds all the data to text boxes.

I've been using the MVCScaffolding feature to create a CRUD UI for my data stored using EF4.1

It works well for basic scenarios and binds all the data to text boxes.

However, I want the "Title" property of my "Person" object to bind to a select list. I was hoping not to have to create a View Model but rather stick with the view binding to the actual Person Model.

public class Person    {
    public string Title { get; set; }
    .......

This is in my view but the selected item doesn't bind correctly. It always shows "Mr" as the selected item even tho开发者_如何学Pythonugh the actual data might be different.

@Html.DropDownListFor(model => model.Title, new SelectList(new[] { "Mr", "Mrs", "Ms", "Miss", "Sir", "Dr", }, Model.Title))

This doesnt work either:

@Html.DropDownList("Title", new SelectList(new[] { "Mr", "Mrs", "Ms", "Miss", "Sir", "Dr", }, Model.Title))

However, this does:

@Html.DropDownList("TitleX", new SelectList(new[] { "Mr", "Mrs", "Ms", "Miss", "Sir", "Dr", }, Model.Title))

But I get an "Object reference not set to an instance of an object." exception when trying to update the record.

How, can I get this to work with minimum disruption to my model or controller?


The first one should be correct. Did you check before your controller returns the view, if the Title field is indeed set to something that exists in the database. Also check spelling and e.g. a dot behind the text. If in your database "Ms." is present, the dropdown will open on the first item, as Ms. does not exist in the list.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号