我有一个下拉列表,我填充在我的视图中。
<div class="form-group"&t; @Html.LabelFor(model => model.AmPm, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListFor(model => model.AmPm, new List<SelectListItem> { new SelectListItem{Text="AM", Value="1"}, new SelectListItem{Text="PM", Value="2"}, new SelectListItem{Text=@"N\A", Value="3", Selected=true}, }, new { id = "amPmDropDownSelect", @class = "form-control" }) @Html.ValidationMessageFor(model => model.AmPm, "", new { @class = "text-danger" }) </div> </div>当我来编辑一个有值的记录时,我希望在模型中存储的值上选择下拉列表。 没有jquery可以做到这一点吗?
当将下拉列表加载到空模型上时,我希望“Text = @”N \ A“,Value =”3“是所选值,并且认为添加Selected = true会起作用,但它总是默认显示第一个在列表中?
I have a drop down list I populate in my view.
<div class="form-group"> @Html.LabelFor(model => model.AmPm, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListFor(model => model.AmPm, new List<SelectListItem> { new SelectListItem{Text="AM", Value="1"}, new SelectListItem{Text="PM", Value="2"}, new SelectListItem{Text=@"N\A", Value="3", Selected=true}, }, new { id = "amPmDropDownSelect", @class = "form-control" }) @Html.ValidationMessageFor(model => model.AmPm, "", new { @class = "text-danger" }) </div> </div>When I come to edit a record, that has a value, I would like the drop downlist to be selected on the value stored in the model. Is it possible to do this without jquery?
when loading the drop down list over an empty model, I wanted "Text=@"N\A", Value="3" to be the selected value and thought adding Selected=true would work but it always defaults to display the first one in the list?
最满意答案
您可以在您的GET操作中将视图模型的AmPm属性设置为您想要选择的选项的值。
public ActionResult Edit(int id) { var vm = new YourViewModel(); vm.AmPm="3"; return View(vm); }现在DropDownListFor辅助方法将选择值为“3”的选项。
如果AmPm属性的类型是int ,则可以设置int值。
vm.AmPm=3;您可以从实体中读取值,并将其设置为3而不是硬编码,例如
public ActionResult Edit(int id) { var e=db.Tasks.Find(id); var vm = new YourViewModel() { Title = e.Title }; vm.AmPm = e.AmPm; // This line sets the selected value return View(vm); }此外,您现在可以从要添加到列表中的第三个SelectListItem对象中删除Selected=true ,该列表将用于构建选项
You can set the AmPm property of your view model to the value of the option you want to select, in your GET action.
public ActionResult Edit(int id) { var vm = new YourViewModel(); vm.AmPm="3"; return View(vm); }Now the DropDownListFor helper method will select the option item with the value "3".
If the type of AmPm property is int, you can set the int value.
vm.AmPm=3;You can read the value from your entity and set that instead of hard coding to 3, For example
public ActionResult Edit(int id) { var e=db.Tasks.Find(id); var vm = new YourViewModel() { Title = e.Title }; vm.AmPm = e.AmPm; // This line sets the selected value return View(vm); }Also you can now remove the Selected=true from the third SelectListItem object you are adding to the list which will be used to build the options
更多推荐
发布评论