如何把一个默认值成DropDownListFor?(How to put a default val

2019-07-30 03:39发布

这是我的下拉列表:

@Html.DropDownListFor(m => m.ReportType, new SelectList(ViewBag.DateRange as List<SelectListItem>, "Value", "Text"), new { @class = "w150" })

我想不通的地方把默认值在那里? 我的默认值是“ThisMonthToDate”

有什么建议?

Answer 1:

如果你有一个模型一定到你的观点,我强烈建议你避免使用ViewBag ,而是一个添加Property到模型/视图模型来保存选择列表项。 所以,你的模型/视图模型将看起来像这样

public class Report
{
   //Other Existing properties also
   public IEnumerable<SelectListItem> ReportTypes{ get; set; }
   public string SelectedReportType { get; set; }
}

然后在您的GET操作方法,可以作为默认选择一个这样设置的值,如果要设定一个选择选项

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标记将具有HTML与值2作为选项选择selected一个。



文章来源: How to put a default value into a DropDownListFor?
标签: c# html razor