【问题标题】:Set values to the items in DropDownListFor in a view为视图中 DropDownListFor 中的项目设置值
【发布时间】:2012-09-22 05:44:10
【问题描述】:

我有这个:

<div class="editor-field">
        <%: Html.DropDownListFor(m => m.Language, new SelectList(new[] { "string1", "string2", "string3", "string4" }, "string1"))%>
</div>

我希望字符串有一些值。例如,string1,有一个 value=1,string2:value=2 等。如何做到这一点?

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

随便用

new List<SelectListItem>(){ new SelectListItem{Text="item1", Value = "valuer1", ... }

或使用 SelectList 但将自定义对象的 Dictionary 或 List 传递给它。

【讨论】:

    【解决方案2】:

    静态绑定

    public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewBag.Message = "Welcome to the Training Courses...";
                List objcourses = new List();
                objcourses.Add("Asp.Net");
                objcourses.Add("MVC");
                objcourses.Add("WCF");
                objcourses.Add("WPF");
                objcourses.Add("C#.Net");
                ViewBag.Courses = new SelectList(objcourses);
                return View();
            }
        }
    
    @{
    ViewBag.Title = "Home Page";
    }
    Index
    @using(@Html.BeginForm(“Index”,”Home”,FormMethod.Get)) {
    Courses List; @Html.DropDownList(“Courses“)
    }
    

    动态绑定

    public class HomeController : Controller
        {
            public ActionResult Index()
            {
                private MovieDBContext db = new MovieDBContext();
                var GenreLst = new List();
                var GenreQry = from d in db.Movies
                               orderby d.Genre
                               select d.Genre;
                GenreLst.AddRange(GenreQry.Distinct());
                ViewBag.Courses = new SelectList(GenreLst);
                return View();
            }
        }
    @{
        ViewBag.Title = "Home Page";
    }
    Index
    
    @using(@Html.BeginForm("Index","Home",FormMethod.Get)) {
    
    Courses List; @Html.DropDownList("Courses")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多