使用Html.DropDownListFor()用的SelectList [英] Using Html.DropDownListFor() with a SelectList

查看:189
本文介绍了使用Html.DropDownListFor()用的SelectList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net使用Html.DropDownListFor帮手MVC 3时,什么是填充的SelectList正确的方法是什么?

我基本上有一个创建的形式,我想对特定字段指定入口值。例如,它是一个电影资料库,我想进入一个类型的能力,但我不希望用户能够进入自己喜欢的东西,所以我承担的SelectList是最好的答案?

这是工作的方法是创建一个新的类的静态方法返回选择列表:

 公共类流派
{
    公共静态列表<串GT; GetGenres()
    {
        清单<串GT; myGenres =新的List<串GT;();
        myGenres.Add(喜剧);
        myGenres.Add(浪漫喜剧);
        myGenres.Add(科幻);
        myGenres.Add(恐怖);        返回myGenres;
    }
}

然后可以使用这样的:

 < D​​IV CLASS =主编场>
        @ Html.DropDownListFor(型号=> model.Genre,新的SelectList(OLL.Models.Genres.GetGenres()))
    < / DIV>

它只是似乎并不喜欢做的正确/最简单的方法?我想我缺少明显的东西在这里...

感谢您可以提供任何帮助。


解决方案

  VAR OG =(从s在DB.Products
 选择新SelectListItem
  {
        文= s.ProductName,
         值= s.ProductID.ToString()
  });
  ViewBag.lstProducts =新的SelectList(getproductname,产品ID,产品名称);
&所述p为H.;
    @ Html.DropDownList(ALBUMID(IEnumerable的< SelectListItem>)ViewBag.lstProducts,新{@id =DRP});
&所述; / P>

What is the correct way to populate a SelectList when using the Html.DropDownListFor helper in ASP.Net MVC 3?

I basically have a "Create" form which I want to specify the entry values on for a particular field. For example, it is a movie database and I want the ability to enter a Genre, but I don't want users to be able to enter what they like, so I assume a SelectList to be the best answer?

A way that works is to create a new class with a static method to return the SelectList:

public class Genres
{
    public static List<string> GetGenres()
    {
        List<string> myGenres = new List<string>();
        myGenres.Add("Comedy");
        myGenres.Add("Romantic Comedy");
        myGenres.Add("Sci-Fi");
        myGenres.Add("Horror");

        return myGenres;
    }
}

Which can then be used like this:

    <div class="editor-field">
        @Html.DropDownListFor(model => model.Genre, new SelectList(OLL.Models.Genres.GetGenres()))
    </div>

It just doesn't seem like the right/easiest way to do it? I think I'm missing something obvious here...

Thanks for any assistance you can provide.

解决方案

 var og = (from s in DB.Products
 select new SelectListItem
  {
        Text = s.ProductName,
         Value = s.ProductID.ToString()
  }); 
  ViewBag.lstProducts = new SelectList(getproductname, "ProductID", "ProductName");
<p>
    @Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.lstProducts, new { @id = "drp" });
</p>

这篇关于使用Html.DropDownListFor()用的SelectList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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