我对 Html.DropDownListFor 有问题。我读过很多类似的questions但我仍然不明白我必须做什么。我不知道如何在下拉列表中将餐食“bb”设置为预选值。
编辑:功能代码:
View 模型
public class OrderForm
{
public int Id { get; set; }
public string MealName { get; set; }
public int OrderCount { get; set; }
public List<SelectListItem> MealOptions { get; set; }
}
Controller
public IActionResult OrderForm()
{
List<SelectListItem> mealOptions = new List<SelectListItem>();
mealOptions.Add(new SelectListItem("aa", "1"));
mealOptions.Add(new SelectListItem("bb", "2"));
mealOptions.Add(new SelectListItem("cc", "3"));
OrderForm viewModel = new OrderForm
{
MealName = "someMeal",
Id = 2,
OrderCount = 5,
MealOptions = mealOptions
};
return View(viewModel);
}
查看
@model OrderForm
@Html.LabelFor(x => x.MealName)
@Html.TextBoxFor(x => x.MealName)
@Html.DropDownListFor(x => x.Id, Model.MealOptions)
HTML 结果
<div>
<label for="MealName">MealName</label>
<input id="MealName" name="MealName" type="text" value="someMeal" />
<select data-val="true" data-val-required="The Id field is required." id="Id" name="Id">
<option value="1">aa</option>
<option selected="selected" value="2">bb</option>
<option value="3">cc</option>
</select>
</div>
最佳答案
工作示例:https://dotnetfiddle.net/MHLuvc
型号
using System.Web.Mvc;
using System.Collections.Generic;
public class OrderForm {
public int Id { get; set; }
public string MealName {get; set;}
public int OrderCount { get; set; }
public int MealItemId {get;set;}
public List<SelectListItem> MealOptions { get; set; }
}
public class MealItem {
public int AltId {get;set;}
public string Name {get;set;}
}
Controller
using System.Linq;
public IActionResult OrderForm(int id)
{
var mealItems = new List<MealItem>() {
new MealItem(){AltId = 0,Name = "aa"},
new MealItem(){AltId = 1,Name = "bb"},
new MealItem(){AltId = 2,Name = "cc"}
};
var mealOptions = mealItems.Select(prop => new SelectListItem() { Text = prop.Name, Value = prop.AltId.ToString() }).ToList();
OrderForm viewModel = new OrderForm
{
MealName = "someMeal",
Id = 4,
OrderCount = 5,
MealItemId = 2, // Set Default MealOption Id
MealOptions = mealOptions
};
return View(viewModel);
}
查看
@model OrderForm
@{
@Html.LabelFor(x => x.MealName)
@Html.TextBoxFor(x => x.MealName)
@Html.DropDownListFor(x => x.MealItemId, Model.MealOptions)
}
关于c# - ASP.NET MVC 预选 Html.DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72330219/