为了账号安全,请及时绑定邮箱和手机立即绑定

MVC3 DropDownListFor-一个简单的例子?

MVC3 DropDownListFor-一个简单的例子?

万千封印 2019-09-21 14:37:54
我DropDownListFor在MVC3应用中遇到问题。我能够使用StackOverflow弄清楚如何使它们出现在View上,但是现在我不知道如何在提交视图模型时捕获其相应属性中的值。为了使它起作用,我必须创建一个具有ID和value属性的内部类,然后必须使用an IEnumerable<Contrib>来满足DropDownListFor参数要求。但是,现在,MVC FW应该如何将在此下拉列表中选择的值映射回我的视图模型的simple string属性中?public class MyViewModelClass{    public class Contrib    {        public int ContribId { get; set; }        public string Value { get; set; }    }    public IEnumerable<Contrib> ContribTypeOptions =         new List<Contrib>        {            new Contrib {ContribId = 0, Value = "Payroll Deduction"},            new Contrib {ContribId = 1, Value = "Bill Me"}        };    [DisplayName("Contribution Type")]    public string ContribType { get; set; }}在我的视图中,将下拉列表放置在页面上,如下所示:<div class="editor-label">    @Html.LabelFor(m => m.ContribType)</div><div class="editor-field">    @Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId,              new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))</div>当我提交表单时ContribType(当然)为null。正确的方法是什么?
查看完整描述

3 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

您应该这样做:


@Html.DropDownListFor(m => m.ContribType, 

                new SelectList(Model.ContribTypeOptions, 

                               "ContribId", "Value"))

哪里:


m => m.ContribType

是结果值所在的属性。


查看完整回答
反对 回复 2019-09-21
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

我认为这会有所帮助:在Controller中获取列表项和选定的值


public ActionResult Edit(int id)

{

    ItemsStore item = itemStoreRepository.FindById(id);

    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 

                                        "Id", "Name",item.CategoryId);


    // ViewBag to pass values to View and SelectList

    //(get list of items,valuefield,textfield,selectedValue)


    return View(item);

}

并在视野中


@Html.DropDownList("CategoryId",String.Empty)


查看完整回答
反对 回复 2019-09-21
?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

要将动态数据绑定到DropDownList中,可以执行以下操作:


如下所示在Controller中创建ViewBag


ViewBag.ContribTypeOptions = yourFunctionValue();

现在在如下所示的视图中使用该值:


@Html.DropDownListFor(m => m.ContribType, 

    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 

                   "Value", Model.ContribTypeOptions.First().ContribId), 

    "Select, please")


查看完整回答
反对 回复 2019-09-21
  • 3 回答
  • 0 关注
  • 356 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信