简体   繁体   中英

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

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

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. In ~/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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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