DropDownList为什么它获取密钥而不是其他
我的模型中有一个非常简单的属性:
现在这个下拉菜单无法正常工作,
@Html.DropDownListFor(m => m.Camp, new SelectList(ViewBag.Camps, "Id", "Name"))
它会返回 < code>null 而不是选择的 Camp,但如果我将其更改为:
@Html.DropDownListFor(m => m.Camp.Id, new SelectList(ViewBag.Camps, "Id", "Name"))
它将返回一个具有正确 Id
的 Camp
对象,但 名称
仍然是空
。
为什么?
UPD:
现在另一个问题是,如果我选择第二种方法,它会搞砸不引人注目的验证。不过我可以根据所选的 ID 找到正确的营地。
I have a property in my model very simple one:
Now this dropDown doesn't work right
@Html.DropDownListFor(m => m.Camp, new SelectList(ViewBag.Camps, "Id", "Name"))
it returns null
instead of a chosen Camp, but if I change that into:
@Html.DropDownListFor(m => m.Camp.Id, new SelectList(ViewBag.Camps, "Id", "Name"))
It would return me a Camp
object with correct Id
, but the Name
would be still null
.
Why?
UPD:
And now another problem is if I choose the second approach it would screw up with unobtrusive validation. Although I'll be able to get the right camp based on the chosen id.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这很正常。仅将
Id
发布到控制器操作。这就是表单内下拉菜单的工作原理。这就是您所能希望达到的目标。然后,您将使用此Id
从数据库中获取相应的 Camp 对象:另外请删除此
ViewBag
并使用真实的视图模型:并在控制器中:
和观点:
That's normal. Only the
Id
is posted to the controller action. That's how dropdown inside forms work. So that's all you can hope to get there. You will then use thisId
to get the corresponding Camp object from the database:Also please get rid of this
ViewBag
and use a real view model:and in the controller:
and the view: