C# 如何将默认值放入DropDownList for?
这是我的下拉列表:C# 如何将默认值放入DropDownList for?,c#,html,razor,C#,Html,Razor,这是我的下拉列表: @Html.DropDownListFor(m => m.ReportType, new SelectList(ViewBag.DateRange as List<SelectListItem>, "Value", "Text"), new { @class = "w150" }) @Html.DropDownListFor(m=>m.ReportType,新的SelectList(ViewBag.DateRange作为列表,“值”,“文本”),新的{@c
@Html.DropDownListFor(m => m.ReportType, new SelectList(ViewBag.DateRange as List<SelectListItem>, "Value", "Text"), new { @class = "w150" })
@Html.DropDownListFor(m=>m.ReportType,新的SelectList(ViewBag.DateRange作为列表,“值”,“文本”),新的{@class=“w150”})
我不知道把默认值放在哪里?我的默认值为“ThisMonthToDate”
有什么建议吗?如果您的视图中有一个模型,我强烈建议您避免使用
ViewBag
,而是在模型/视图模型中添加一个属性来保存选择列表项。因此,您的模型/视图模型将如下所示
public class Report
{
//Other Existing properties also
public IEnumerable<SelectListItem> ReportTypes{ get; set; }
public string SelectedReportType { get; set; }
}
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标记将使用值为2的选项进行HTML选择,该选项为selected
one