【发布时间】:2012-06-27 23:18:36
【问题描述】:
这是我的下拉列表:
@Html.DropDownListFor(m => m.ReportType, new SelectList(ViewBag.DateRange as List<SelectListItem>, "Value", "Text"), new { @class = "w150" })
我不知道在哪里放置默认值?我的默认值是“ThisMonthToDate”
有什么建议吗?
【问题讨论】:
这是我的下拉列表:
@Html.DropDownListFor(m => m.ReportType, new SelectList(ViewBag.DateRange as List<SelectListItem>, "Value", "Text"), new { @class = "w150" })
我不知道在哪里放置默认值?我的默认值是“ThisMonthToDate”
有什么建议吗?
【问题讨论】:
如果您的视图绑定了模型,我强烈建议您避免使用ViewBag,而是将Property 添加到您的模型/视图模型中以保存选择列表项。所以你的模型/视图模型看起来像这样
public class Report
{
//Other Existing properties also
public IEnumerable<SelectListItem> ReportTypes{ get; set; }
public string SelectedReportType { get; set; }
}
然后在你的 GET Action 方法中,你可以设置 value ,如果你想像这样设置一个选择选项作为默认选择一个
public ActionResult EditReport()
{
var report=new Report();
//The below code is hardcoded for demo. you mat replace with DB data.
report.ReportTypes= new[]
{
new SelectListItem { Value = "1", Text = "Type1" },
new SelectListItem { Value = "2", Text = "Type2" },
new SelectListItem { Value = "3", Text = "Type3" }
};
//Now let's set the default one's value
objProduct.SelectedReportType= "2";
return View(report);
}
在您的强类型视图中,
@Html.DropDownListFor(x => x.SelectedReportType,
new SelectList(Model.ReportTypes, "Value", "Text"), "Select Type..")
以上代码生成的 HTML Markup 将选择带有值为 2 的选项的 HTML 选择 selected 1。
【讨论】: