[英]Get the drop downListFor show the selected value in asp.net mvc
I have a DropDownListFor is like this below 我有一个DropDownListFor是这样的
@Html.DropDownListFor(m => m._dayOfWeek, new SelectList(Model._dayOfWeekList, "Value", "Text"))
in Model
_dayOfWeek is string
_dayOfWeekList is List<selectlistItem>
now in dayOfWeekList
is getting created in controller and it can have many values but max seven values 现在在控制器中创建了
dayOfWeekList
,它可以有多个值,但最多七个值
Value - 0 Text - Monday 价值-0文字-星期一
Value - 1 Text - Tuesday 值-1文字-星期二
Value - 2 Text - Wednesday 值-2文字-星期三
and so on ... 等等 ...
now in _dayOfWeek string i can assign value or text - depending on the value in _dayOfWeek
--- the dropdown should be able to show that option 现在在_dayOfWeek字符串中,我可以分配值或文本-取决于
_dayOfWeek
的值-下拉列表应该能够显示该选项
when the page is loaded drop down is always showing Monday as default . 当页面加载时,下拉菜单始终默认显示星期一。
how to make the drop down show that option which is there in _dayOfWeek
string 如何使下拉菜单显示
_dayOfWeek
字符串中存在的选项
First, don't create a new SelectList
. 首先,不要创建新的
SelectList
。 Razor can handle this itself, and it's better to let it. 剃刀可以自己处理,最好让它处理。 All
DropDownListFor
requires is IEnumerable<SelectListItem>
, which you already have: DropDownListFor
所需的全部是IEnumerable<SelectListItem>
,您已经拥有:
@Html.DropDownListFor(m => m._dayOfWeek, Model._dayOfWeekList)
Second, the value assigned is determined based on ModelState
, which is composed of values from Request
, ViewData
/ ViewBag
and, as a last resort, Model
. 其次,根据
ModelState
确定分配的值,该模型状态由Request
, ViewData
/ ViewBag
的值以及作为最后选择的Model
。 As a result, you should ensure that your view's model has the appropriate value set for that property and that it aligns with the possible option values in your List<SelectListItem>
. 因此,你应该确保您的视图模型具有该属性设置适当的值,它在与可能的选项值对齐
List<SelectListItem>
Then, ensure that you do not have any conflicts from accepting a param like _dayOfWeek
to your action method or something like ViewBag._dayOfWeek
being set to some value. 然后,确保从接受
_dayOfWeek
类的参数到您的操作方法,或者将诸如ViewBag._dayOfWeek
类的ViewBag._dayOfWeek
设置为某个值,您没有任何冲突。 In both cases, casing does not matter, so _dayOfWeek
== _DayOfWeek
== _DAYOFWEEK
. 在两种情况下,大小写都不重要,因此
_dayOfWeek
== _DayOfWeek
== _DAYOFWEEK
。
Ok I got the answer to that . 好吧,我得到了答案。 without using viewbag or viewdata
不使用viewbag或viewdata
foreach (var item in model._dayOfWeekList)
{
if (item.Text == model._dayOfWeek)
{
item.Selected = true;
}
}
thnaks to others also for their time 也为他们的时间向他人致意
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.