How to put a default value into a DropDownListFor?

荒凉一梦 提交于 2019-12-20 06:39:53

问题


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'

Any suggestions?


回答1:


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. So your Model/ViewModel will looks like this

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

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.



来源:https://stackoverflow.com/questions/11210727/how-to-put-a-default-value-into-a-dropdownlistfor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!