单个控制器是多个模型的视图

时间:2016-02-05 20:16:16

标签: c# entity-framework model-view-controller dynamic

我是MVC和EF的新手,但我有一组模型代表所有具有相同结构的查找表

public int ID {get; set;}
public string Value {get; set;}
public bool IsActive {get; set;}

不是为每个编写一个控制器和视图,而是创建一个控制器和视图,这是由之前选择的值定义的。

因此,如果我的两个查找是性别和状态,并且下拉列表中包含这些值 然后,我可以获取所选选项的名称,然后动态绑定到模型

因此,而不是具有状态status = new状态,其对象对象=新对象,其中对象已通过在上一个下拉列表中选择状态来定义

1 个答案:

答案 0 :(得分:1)

绝对有可能。有几种方法可以实现这一目标。你可以拥有一个EditorTemplate,其中包含显示下拉列表所需的一切。在〜/ Views / Shared / EditorTemplates / DropDown.cshtml

@model string
@{
    Layout = null;
    List<SelectListItem> ListItems = (List<SelectListItem>)ViewBag.ListItems;
}
// not sure what the syntax for a dropdown is, I don't use them
@Html.SelectFor(m => Model, ListItems)

然后在你看来

@Html.EditorFor(m => m.Status, "DropDown", new { ListItems = MyModel.StatusSelectListItems })
@Html.EditorFor(m => m.Gender, "DropDown", new { ListItems = MyModel.GenderSelectListItems })

在模型中,您可以选择选项:

public class MyModel
{
    // other stuff
    public static List<SelectListItem> GenderSelectListItems = new List<SelectListItem> 
    { 
        new SelectListItem{ Value = "Male", Text = "Male" },
        new SelectListItem{ Value = "Female", Text = "Female" }
    };
    // etc
}