MVC3 DropDownListFor-一个简单的例子?

我的 MVC3应用程序 DropDownListFor出了点问题。我曾经能够使用 StackOverflow 来弄清楚如何让它们出现在视图中,但是现在我不知道如何在视图模型中捕获提交时相应属性中的值。为了使其正常工作,我必须创建一个具有 ID 和 value 属性的内部类,然后我必须使用 IEnumerable<Contrib>来满足 DropDownListFor参数的要求。然而,现在 MVC FW 应该如何将这个下拉列表中选择的值映射回我的视图模型中的简单字符串属性呢?

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(当然)为空。

做这件事的正确方法是什么?

229458 次浏览

You should do like this:

@Html.DropDownListFor(m => m.ContribType,
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

For binding Dynamic Data in a DropDownList you can do the following:

Create ViewBag in Controller like below

ViewBag.ContribTypeOptions = yourFunctionValue();

now use this value in view like below:

@Html.DropDownListFor(m => m.ContribType,
new SelectList(@ViewBag.ContribTypeOptions, "ContribId",
"Value", Model.ContribTypeOptions.First().ContribId),
"Select, please")

I think this will help : In Controller get the list items and selected value

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

and in View

@Html.DropDownList("CategoryId",String.Empty)
     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value