简体   繁体   English

如何将默认值放入DropDownListFor?

[英]How to put a default value into a DropDownListFor?

this is my drop down list: 这是我的下拉列表:

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

I cannot figure out where to put the default value in there? 我不知道将默认值放在哪里? My default value would be 'ThisMonthToDate' 我的默认值为“ ThisMonthToDate”

Any suggestions? 有什么建议么?

If you have a Model bounded to your view, I strongly recommend you to avoid using ViewBag and instead add a Property to your Model/ViewModel to hold the Select List Items. 如果您有绑定到视图的模型,强烈建议您避免使用ViewBag ,而ViewBag模型/ ViewModel中添加一个Property以容纳“选择列表项”。 So your Model/ViewModel will looks like this 所以您的Model / ViewModel看起来像这样

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

Then in your GET Action method, you can set the value , if you want to set one select option as the default selected one like this 然后,在GET Action方法中,您可以设置值,如果您想将一个选择选项设置为默认的这样一个选择选项

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);    
}

and in your Strongly typed view , 在您的强类型视图中,

@Html.DropDownListFor(x => x.SelectedReportType, 
     new SelectList(Model.ReportTypes, "Value", "Text"), "Select Type..")

The HTML Markup generated by above code will have the HTML select with the option with value 2 as selected one. 通过上面的代码生成的HTML标记将具有HTML与值2作为选项选择selected一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM