如何将默认值放入DropDownListFor? [英] How to put a default value into a DropDownListFor?

查看:49
本文介绍了如何将默认值放入DropDownListFor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的下拉列表:

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

我不知道默认值放在哪里?我的默认值为"ThisMonthToDate"

I cannot figure out where to put the default value in there? My default value would be 'ThisMonthToDate'

有什么建议吗?

推荐答案

如果您的视图绑定了模型,强烈建议您避免使用 ViewBag ,而是添加一个 Property到您的Model/ViewModel来保存选择列表项".所以您的Model/ViewModel看起来像这样

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

然后,如果要设置一个选择选项作为默认选择的选项,则可以在GET Action方法中设置该值

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

在您的强类型视图中,

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

由上述代码生成的HTML标记将使HTML选择带有值为2的选项,而 selected 一.

The HTML Markup generated by above code will have the HTML select with the option with value 2 as selected one.

这篇关于如何将默认值放入DropDownListFor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆