数据绑定到partialview的DropDownList的MVC3中使用viewbag [英] bind data to dropdownlist of partialview in MVC3 using viewbag

查看:454
本文介绍了数据绑定到partialview的DropDownList的MVC3中使用viewbag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建MVC 3的局部视图控件使用在我的整个应用此控件。在我的局部视图有2下拉列表一个国家与另一个国家的状态。但是,当我用这个我得到error.please提醒我怎么可以在MVC中的完美的用户控制?如何从SQL视图通过包数据绑定到DDL?

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?

感谢。

推荐答案

您需要的IEnumerable要显示在DDL,
试试下面的例子(我没有测试过,某些类型的错误可能是在那里)

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

定义你的模型一样,

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);
}

和在视图,

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

这篇关于数据绑定到partialview的DropDownList的MVC3中使用viewbag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆