Implementing Dropdownlist on Asp.net MVC 3 from viewModel

前端 未结 2 491
终归单人心
终归单人心 2021-01-07 13:25

I\'m new to .net and mvc platform, i have so many int fields that stores some dropdownlist values, i\'ve created fields int type due to database size so i\'m implementing dr

相关标签:
2条回答
  • 2021-01-07 13:54

    If I was you, I should use a dictionary key / displayName like this for the SelectList :

    one static member (as it is static...) :

    static Dictionary<int, string> CitiesDict = new Dictionary<int, string>()
        {
            { -1 , "--Select One---"},
            { 0 ,"Chicago"},
            { 1 ,"New York"},
            { 2 ,"Zimbabwe"},
        };
    

    One Property for the dropdown :

    public SelectList Cities { get; set; }
    

    Initialized in constructor like this :

    Cities = new SelectList(CitiesDict , "Key", "Value", -1);
    

    Then in the view for editing :

    @Html.DropDownListFor(model => model.Property.City, Model.Cities) 
    

    And for displaying:

    @(CitiesDict.ContainsKey(Model.City) ? CitiesDict[Model.City] : "")
    
    0 讨论(0)
  • 2021-01-07 14:07

    I haven't used Razor syntax yet (still on MVC2), but I believe this part is wrong:

    @Html.DropDownListFor(model => model.Property.City,
            new SelectList(Model.Cities,"Value","Text"))
    

    You need to tell the view engine what values to populate the select list with (the value attribute and text associated with the option element), but I don't know the correct MVC3 syntax to help you fix it. Hopefully someone else can...

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