DropDownListFor从模型默认选择项 [英] DropDownListFor default selected item from model
问题描述
我必须绑定到一个模型成员,以及可选择的项目列表的DropDownListFor。结合此成员的作品,但我似乎无法弄清楚是如何显示模型的当前值在页面加载时。
I have a DropDownListFor bound to a model member as well as a list of items to choose from. The binding to this member works, but what I can't seem to figure out is how to display the current value of the model when the page loads.
查看
@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.statuses)
控制
List<SelectListItem> statuses = new List<SelectListItem>();
statuses.Add(new SelectListItem { Text = "Approved", Value = "Approved" });
statuses.Add(new SelectListItem { Text = "Declined", Value = "Declined" });
statuses.Add(new SelectListItem { Text = "Pending", Value = "Pending" });
ViewBag.ClaimStatus = statuses;
添加optionLabel参数不工作,并返回一个空值,并在SelectListItem传递作为optionLabel参数也不行。
Adding the optionLabel argument doesn't work and returns a null value, and passing in a SelectListItem as the optionLabel parameter doesn't work either.
@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.methodofpayment, model.MethodOfPayment)
我希望页面显示提交相同的值,如果他们不改变列表项。
I want the page to submit the same value shown if they don't change the list item.
编辑:
感谢你们,一定是一个名称冲突。
我搞砸了问我的问题有点,因为我有两个下拉列表,我必须抄错了。
Thanks you guys it must have been a name conflict.
I messed up asking my question a bit cause I have two drop down lists and I must have copied the wrong one.
更改的code:
控制器:
The Changed Code:
Controller:
List<SelectListItem> statuses = new List<SelectListItem>();
statuses.Add(new SelectListItem { Text = "Approved", Value = "Approved" });
statuses.Add(new SelectListItem { Text = "Declined", Value = "Declined" });
statuses.Add(new SelectListItem { Text = "Pending", Value = "Pending" });
ViewBag.ClaimStatuses = statuses;
查看:
@Html.DropDownListFor(model => model.ClaimStatus, (List<SelectListItem>)ViewBag.ClaimStatuses)
它制造复数,它的作品。
Made it plural and it works.
推荐答案
有时,它可能发生,你可能已经为不同的控件/变量使用相同的名称,它可能互相冲突。
Sometimes it may happen that you might have used the same name for different controls/variables and it might conflict with each other.
在你情况下,模型属性名在冲突 MethodofPayment
和你ViewBag名称 methodofpayment
结果我猜。
In you case the Model property name MethodofPayment
and your ViewBag name methodofpayment
results in conflict I guess.
试着改变你的ViewBag名字像 ViewBag.paymentmode
和尝试。
Try changing your ViewBag name to something like ViewBag.paymentmode
and try it.
@Html.DropDownListFor(model => model.MethodofPayment, (List<SelectListItem>)ViewBag.paymentmode)
这篇关于DropDownListFor从模型默认选择项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!