MVC3 模型绑定到选择列表

发布于 2024-11-04 11:44:21 字数 856 浏览 4 评论 0原文

我一直在使用 MVCScaffolding 功能为使用 EF4.1 存储的数据创建 CRUD UI。

它非常适合基本场景,并将所有数据绑定到文本框。

但是,我希望“Person”对象的“Title”属性绑定到选择列表。我希望不必创建视图模型,而是坚持将视图绑定到实际的人员模型。

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

这是我的观点,但所选项目未正确绑定。即使实际数据可能不同,它始终将“Mr”显示为所选项目。

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

这也不起作用:

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

但是,这确实有效:

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

但是我得到一个“对象引用未设置为对象的实例”。尝试更新记录时出现异常。

我怎样才能让它在对我的模型或控制器造成最小干扰的情况下工作?

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 though 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蘸点软妹酱 2024-11-11 11:44:21

第一个应该是正确的。在控制器返回视图之前,您是否检查过“标题”字段是否确实设置为数据库中存在的内容。还要检查拼写,例如文本后面的点。如果在您的数据库中“女士”。如果存在,则下拉菜单将在第一项上打开,因为列表中不存在 Ms.。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文