如何动态绑定视图中的dropdownlist? mvc4

时间:2014-04-02 10:00:07

标签: html asp.net-mvc-4 razor

我想在我的视图中替换此代码

代码:

<label for="name">Lead Source</label><select name="Lead_Source" id="Lead_Source" rel="2">
                                        <option value="1">News Papers </option>
                                        <option value="2">Internet</option>
                                        <option value="3">Social networking</option>
                                         <option value="4">Others</option>
                                        </select> 

我想用Dropdownlist替换,所以我会动态地绑定数据,因为我正在努力工作。

我试过这样的话:

<label for="name">Lead Source</label> @Html.DropDownListFor(c=>c.Lead_Source, Model.Lead_Source_List,"--Select Source--");

我更换静态代码后出现的错误是

 CS1928: 'System.Web.Mvc.HtmlHelper<Ibs.Iportal.Iwise.Web.Models.LeadSortModel>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, object)' has some invalid arguments

编辑:我正在传递一个模型来查看包含可枚举列表数据的Lead_Source_List的模型

此致

1 个答案:

答案 0 :(得分:0)

你应该创建一个视图模型并制作强类型视图,在你的动作中做这样的事情:

public ActionResult YourAction(int id)
{
    var model = new MyViewModel();
    using (var db = new SomeDataContext())
    {
        // Get the boxer you would like to edit from the database
        model.Boxer = db.Boxers.Single(x => x.BoxerId == id);

        // Here you are selecting all the available weight categroies
        // from the database and projecting them to the IEnumerable<SelectListItem>
        model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
        {
            Value = x.WeightCategoryId.ToString(),
            Text = x.Name
        })
    }
    return View(model);
}

这个块正在填充选择列表项:

model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
            {
                Value = x.WeightCategoryId.ToString(),
                Text = x.Name
            })

并分配给模型

现在以这种方式使用:

@model MyViewModel
@Html.DropDownListFor(
    x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
    Model.WeightCategories
)