MVC3 DropDownListFor-一个简单的例子?

我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。


正确的方法是什么?


万千封印
浏览 358回答 3
3回答

慕沐林林

您应该这样做:@Html.DropDownListFor(m => m.ContribType,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new SelectList(Model.ContribTypeOptions,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"ContribId", "Value"))哪里:m => m.ContribType是结果值所在的属性。

明月笑刀无情

我认为这会有所帮助:在Controller中获取列表项和选定的值public ActionResult Edit(int id){&nbsp; &nbsp; ItemsStore item = itemStoreRepository.FindById(id);&nbsp; &nbsp; ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Id", "Name",item.CategoryId);&nbsp; &nbsp; // ViewBag to pass values to View and SelectList&nbsp; &nbsp; //(get list of items,valuefield,textfield,selectedValue)&nbsp; &nbsp; return View(item);}并在视野中@Html.DropDownList("CategoryId",String.Empty)

阿波罗的战车

要将动态数据绑定到DropDownList中,可以执行以下操作:如下所示在Controller中创建ViewBagViewBag.ContribTypeOptions = yourFunctionValue();现在在如下所示的视图中使用该值:@Html.DropDownListFor(m => m.ContribType,&nbsp;&nbsp; &nbsp; new SelectList(@ViewBag.ContribTypeOptions, "ContribId",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Value", Model.ContribTypeOptions.First().ContribId),&nbsp;&nbsp; &nbsp; "Select, please")
打开App,查看更多内容
随时随地看视频慕课网APP