bind data to dropdownlist of partialview in MVC3 using viewbag

空扰寡人 提交于 2019-12-25 05:15:28

问题


I want to create a partial view control in MVC 3 to use this control in my whole application. In my partial view there is 2 drop down lists one for country and another for states. But when i used this i am getting error.please advise how can i make a perfect user control in MVC? How can i bind data to DDL from sql through view bag?

Thanks.


回答1:


You need IEnumerable to be displayed in DDL, Try the following example (I have not tested, some type errors may be there)

Define your model like,

public class MyModel
{
public SchduleEnum SelectedCountry{ get; set; }
public ProgramCatagory SelectedState{ get; set; }
private IEnumerable<SelectListItem> stateList;
private IEnumerable<SelectListItem> countriesList;

public IEnumerable<SelectListItem> CountriesList;
{
    get { return this.countriesList;}
}

public IEnumerable<SelectListItem> StateList
{
    get { return this.stateList }
}

private void SetCountryList(IEnumerable<string> countries)
{
    List<SelectListItem> items=new List<SelectListItem>();
    countries.ToList().ForEach(s=>{            
        items.Add(new SelectListItem()
            {
                Text = s,
                Value = s
            });
    });
    this.countriesList = items;
}

private void SetStateList(IEnumerable<string> states)
{
    List<SelectListItem> items = new List<SelectListItem>();
    states.ToList().ForEach(s =>
    {
        items.Add(new SelectListItem()
        {
            Text = s,
            Value = s
        });
    });
    this.stateList= items;
}
}

Define your controller action like,

public PartialViewResult GetCountryList()
{

    MyModel model = new MyModel();
var countries= *** ;//service call to get countries list
var states = *** ;//service call to get stateslist
    model.SetCOuntryList(countries);
    model.SetStateList(states);
    return View(model);
}

and in the View,

<%:Html.DropDownListFor(m=>m.SelectedCountry,Model.countriesList)%>
<%:Html.DropDownListFor(m=>m.SelectedSState,Model.stateList) %>


来源:https://stackoverflow.com/questions/9392883/bind-data-to-dropdownlist-of-partialview-in-mvc3-using-viewbag

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