How to put a default value into a DropDownListFor?

2019-03-03 16:41发布

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?

标签: c# html razor
1条回答
走好不送
2楼-- · 2019-03-03 16:56

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.

查看更多
登录 后发表回答