DropDownListFor 选择不起作用——再次
是的,我知道,这个问题已被问/回答了 34798796873.5 次。我浏览了所有 3 无数的内容,但仍然有问题。我在这里缺少什么?
我尝试了几种方法,但没有一个有效。以下是我的最新尝试:
<%:Html.DropDownList("Author",
Model.AuthorItems.Select(i =>
new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString(),
Selected = i.Id == Model.Author.Id
}), "無し")%>
<%:Html.DropDownListFor(m => m.Author,
new SelectList(Model.AuthorItems,
"Id",
"Name",
Model.Author),
"無し") %>
我的视图模型非常简单:
public class EditArticleViewModel
{
public AuthorItem Author { get; set; }
public IList<AuthorItem> AuthorItems { get; set; }
public class AuthorItem
{
public int Id { get; set; }
public string Name { get; set; }
}
}
我确保我的操作正常工作;果然,Author 的 Id 为 5,AuthorItems 的条目的 Id 为 5。
我什至尝试在模型中重写 Equals 和 GetHashCode。
哈哈哈哈!!1
Yeah, I know, this question's been asked/answered 34798796873.5 times. I looked through all 3 bajillion of them, and I still have the problem. What am I missing here?
I tried several approaches and none of them work. Here are my latest attempts:
<%:Html.DropDownList("Author",
Model.AuthorItems.Select(i =>
new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString(),
Selected = i.Id == Model.Author.Id
}), "無し")%>
<%:Html.DropDownListFor(m => m.Author,
new SelectList(Model.AuthorItems,
"Id",
"Name",
Model.Author),
"無し") %>
My view model is very straightforward:
public class EditArticleViewModel
{
public AuthorItem Author { get; set; }
public IList<AuthorItem> AuthorItems { get; set; }
public class AuthorItem
{
public int Id { get; set; }
public string Name { get; set; }
}
}
I made sure my action is working correctly; sure enough, Author has an Id of 5, and AuthorItems has an entry whose Id is 5.
I even tried overriding Equals and GetHashCode in the model.
Blahhhhh!!1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的视图模型中替换:
并
在您的视图中将下拉列表绑定到此
SelectedAuthorId
:现在,只要您在控制器操作中提供有效的
SelectedAuthorId
值即可:HTML呈现下拉列表的助手将正确地从列表中预选择具有给定 ID 的项目。
原因是在下拉列表中您只能选择单个值(标量类型),而不能选择整个作者(提交表单时 HTTP 请求中发送的所有内容都是该选定值)。
In your view model replace:
with
and in your view bind the dropdown list to this
SelectedAuthorId
:Now as long as you provide a valid
SelectedAuthorId
value in your controller action:The HTML helper that renders the dropdown will correctly preselect the item from the list that has this given id.
The reason for this is that in a dropdown list you can select only a single value (a scalar type) and not an entire Author (all that is sent in the HTTP request when you submit the form is this selected value).
DropDownList/DropDownListFor 使用的 ModelState 值。因此在控制器中设置ViewDataDictionary selectedValue。
看代码简单。
ViewData 键“Author”正在使用所选值的模型状态绑定。
希望这有帮助。
DropDownList/DropDownListFor used ModelState value. So set ViewDataDictionary selectedValue in controller.
View code simple.
ViewData key "Author" is using model state binding for selected value.
Hope this help.