简体   繁体   English

单一控制器的多种模型视图

[英]Single Controller an View for multiple Models

I am new to MVC and EF, but i have a group of models that represent lookup tables that all have the same structure 我是MVC和EF的新手,但是我有一组模型代表表示具有相同结构的查找表

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

Rather than writing one Controller and View for each is there a way to create one, that is defined by a previous selected value. 除了为每个控制器和视图编写一个控制器和视图外,还有一种方法来创建一个控制器,该方法由先前选择的值定义。

So if 2 of my lookups are Gender and Status and a dropdown with these values can I then take the name of the selected option and then dynamically bind to the model 因此,如果我的查询中有两个是“性别”和“状态”,并且带有这些值的下拉菜单,那么我可以选择所选选项的名称,然后动态绑定到模型

so rather than having Status status = new Status its Object object = new Object where object has been defined by the selection of Status in the previous dropdown 因此,与其让Status成为Status = new Status而不是其Object对象= new Object,其中对象是通过上一个下拉列表中的Status选择来定义的

It is definitely possible. 绝对有可能。 There are several ways you could achieve this. 有几种方法可以实现此目的。 You could have an EditorTemplate with everything you need to display your dropdown. 您可能拥有一个EditorTemplate,其中包含显示下拉菜单所需的所有内容。 In ~/Views/Shared/EditorTemplates/DropDown.cshtml 在〜/ 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)

Then in your view 然后在您看来

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

Where in your model you would have the selection options: 您可以在模型中的哪个位置进行选择:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM