How to put a default value into a DropDownListFor?

后端 未结 1 1526
自闭症患者
自闭症患者 2021-01-28 14:38

this is my drop down list:

@Html.DropDownListFor(m => m.ReportType, new SelectList(ViewBag.DateRange as List, \"Value\", \"Text\"), new          


        
1条回答
  •  执笔经年
    2021-01-28 15:01

    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 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.

    0 讨论(0)
提交回复
热议问题