DropDownListFor with a custom attribute with - in attribute name?

☆樱花仙子☆ 提交于 2019-12-02 20:11:53

Use an underscore instead

@data_placeholder = "whatever"

Since Mvc3 "_" is replaced with "-" when rendered.

This works fine as underscores are not acceptable in attribute names in html.

Ah, it's easy.
The mistake was to declare a dictionary of <string, string> instead of a dictionary of <string, object> (and to use variables instead of properties in cOption)...


With dictionary of <string, string> it uses the object "paramlist" overload, instead of IDictionary<string, object> ;)

@Html.DropDownListFor(model => model.Title, new SelectList(Model.ls, "value", "text"), Model.nvc)

 <!--
 @Html.DropDownList("myIdAndName", new SelectList(Model.ls, "value", "text"), Model.nvc)
 -->




    public ActionResult Index()
    {
        cHomeModel HomeModel = new cHomeModel();

        HomeModel.nvc.Add("class", "chzn-select");
        HomeModel.nvc.Add("data-placeholder", "Choose a customer");
        HomeModel.nvc.Add("style", "width:350px;");
        HomeModel.nvc.Add("tabindex", "1");
        HomeModel.nvc.Add("multiple", "multiple");
        HomeModel.nvc.Add("id", "lol");


        cOption option = null;


        for (int i = 0; i < 10; ++i)
        {
            option = new cOption();

            option.value = i.ToString();
            option.text = "text" + i.ToString();

            HomeModel.ls.Add(option);
        }


        return View(HomeModel);
    }





    public class cOption
    {
        public string value
        {
            get;
            set;
        }

        public string text
        {
            get;
            set;
        }

    }


    public class cHomeModel
    {
        public string Title = "MyDropDownListName";
        public List<cOption> ls = new List<cOption>();


        public System.Collections.Generic.Dictionary<string, object> nvc = new System.Collections.Generic.Dictionary<string, object>();

    }

or more Linqiq:

public ActionResult Index()
{
    cHomeModel HomeModel = new cHomeModel();

    HomeModel.nvc.Add("class", "chzn-select");
    HomeModel.nvc.Add("data-placeholder", "Choose a customer");
    HomeModel.nvc.Add("style", "width:350px;");
    HomeModel.nvc.Add("tabindex", "1");
    HomeModel.nvc.Add("multiple", "multiple");
    HomeModel.nvc.Add("id", "lol");


    HomeModel.ls = System.Linq.Enumerable.Range(0, 9)
            .Select(x => new cOption() { text = x.ToString(), value = x.ToString() })
            .ToList();


    // or otherwise: 
    HomeModel.ls = (
                 from i in System.Linq.Enumerable.Range(0, 9)
                 select new cOption() { text = i.ToString(), value = i.ToString() }
    ).ToList();


    return View(HomeModel);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!