问题
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