从ASP.Net MVC3中的DropDown读取数据

时间:2012-05-12 05:42:19

标签: asp.net-mvc-3

我正在使用Database First方法进行ASP.net MVC 3(空类型而不是互联网类型)...

我需要的是

第1步: 我只是使用下拉列表来显示公司所在的各个位置。该列表来自Organization表,Location在此Oranization Table中只有一个字符串字段,

第2步: 当用户正在进行注册时,下拉列表将显示位置..现在,用户选择印度,然后此值(位置名称)应存储在UserLogin表中...

现在如何从下拉列表中读取值,我希望您能够理解我的问题并提前感谢

1 个答案:

答案 0 :(得分:2)

我会使用视图模型:

public class RegisterViewModel
{
    public string LocationName { get; set; }
    public IEnumerable<SelectListItem> Locations { get; set; }
}

然后是一个将为视图提供服务的控制器操作:

public ActionResult Index()
{
    var model = new RegisterViewModel();
    model.Locations = new SelectList(dbcontext.Organization_Details, "OName", "OLocation");
    return View(model);
}

然后是相应的强类型视图:

@model RegisterViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.LocationName)
    @Html.DropDownListFor(x => x.LocationName, Model.Locations)
    <button type="submit">OK</button>
}

最后是在提交表单时调用的控制器操作:

[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
    // model.LocationName will contain the selected location here
    ...
}