Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC: Best way to populate Html .DropDownList

I'm looking for a sound philosophy for bringing dynamic data into a view to populate a dropdownlist. Would it be a good idea to create a model object for dropdownlists and other "overhead" data or use a viewbag?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Example for guidance:

I think the best way to achieve what you're after would be to use a ViewModel. You'd load the stuff you want to display in your View through this. So you'd create a dropdownlist with your accountlist which will be loaded in your controller. You'll also have your IEnumerable PErsoncontact in there which will also be loaded in your controller. Then your controller will pass the ViewModel to the View. You can use this as a guide.

ViewModel:

public class PersonViewModel
{
    public int PersonID {get;set;}
    public List<SelectListItem> PersonContactList {get;set;}
    public IEnumerable<TypesAvail> TypesAvails{get;set;}
}

Dropdownlist in Razor View :

@Html.DropDownListFor(m => m.PersonID , Model.PersonContactList )

Edit:- This is an example .Yes you can create a new class in same Model.

public class TypesAvail
{
     public String TypeNme { get; set; }
    public long TypeID { get; set; }
    public int NumSelected { get; set; }
    public int TypeCount { get; set; }
    public IEnumerable<SelectListItem> CarsAvail 
    {
        get
        {
            return new SelectList(
                    Enumerable.Range(0, TypeCount+1)
                    .OrderBy(typecount => typecount)
                    .Select(typecount => new SelectListItem
                    {
                        Value = typecount.ToString(),
                        Text = typecount.ToString()
                    }), "Value", "Text");
        }
    } 
}

Dropdownlist in Razor View :

@Html.DropDownListFor(m=> m.NumSelected, Model.CarsAvail)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...