使用实体框架(.edmx 模型)为 MVC3 创建下拉列表 &剃刀视图&&将一条数据库记录插入多个表 [英] Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

查看:23
本文介绍了使用实体框架(.edmx 模型)为 MVC3 创建下拉列表 &剃刀视图&&将一条数据库记录插入多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了关于如何在 MVC 3 中使用 Razor 视图创建下拉列表的 100 篇文章后,我找不到适合我的情况.

情况:我最终是想创建一个视图来将员工添加到数据库中.

Situation: I am ultimately trying to create a View to Add an Employee to a Database.

这是我正在使用的 .EDMX 模型的图像(create() 将使用的表):

Here is an image of the .EDMX Model that I am using (the tables that will be used by the create().):

目标:

  1. 创建一个员工(我有 Create.cshtml(强类型),用 StaffNotify 复选框的局部视图制作){我在来自创建视图的通知局部视图中使用单独的 @model,不确定是否那是安全的???@model ShadowVenue.Models.Employee &@model ShadowVenue.Models.StaffNotify)

  1. Create an Employee (I have the Create.cshtml (strongly typed) made with a Partial View for the StaffNotify Checkboxes) {I am using a separate @model in the Notify Partial View from the Create View not sure if that is safe??? @model ShadowVenue.Models.Employee & @model ShadowVenue.Models.StaffNotify)

为 StaffTypeId 创建一个下拉框(将插入表StaffType"(具有 1 对多关系)中的 [StaffTypeId] 值,但会在下拉列表中显示 [Type] 字符串值)

Create a Dropdown box for StaffTypeId (that will insert the [StaffTypeId] value from the Table "StaffType" (which has a 1 to many relationship), but will show the [Type] string value in the dropdown)

为 GenderId 创建一个下拉框(这将插入表Genders"(具有 1 对多关系)中的 [GenderId] 值,但会在下拉列表中显示 [Gender] 字符串值)

Create a Dropdown box for GenderId (that will insert the [GenderId] value from the Table "Genders" (which has a 1 to many relationship), but will show the [Gender] string value in the dropdown)

将记录插入数据库(我将员工通知放在一个单独的表中,在 StaffId 主键上有 1 对 1 的关系)

Insert the Record into the database (I have the Staff Notifications in a separate table with a 1 to 1 relationship on the StaffId Primary Key)

我似乎在使用控制器代码时遇到了问题.

I seem to be having the trouble with the Controller code for this.

我不确定是否应该在 EDMX 模型中创建存储过程,或者想出一些查询或方法语法,不确定哪种方法最好.

I am not sure if I should create Stored Procedure within the EDMX model, or come up with some query or method syntax, not sure which is the best way.

这是我第一个使用实体框架模型的大型 MVC3 应用程序.

This my First Large MVC3 App using Entity Framework Model.

(如果您需要知道任何导航属性名称以帮助解决问题,请告诉我,我会提供给您)

(if you need to know any of the Navigation Property Names in order to help with the solution just let me know, I will provide them to you)

推荐答案

不要将 db 模型直接传递给您的视图.你很幸运使用MVC,所以使用视图模型进行封装.

Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.

像这样创建一个视图模型类:

Create a view model class like this:

public class EmployeeAddViewModel
{
    public Employee employee { get; set; }
    public Dictionary<int, string> staffTypes { get; set; }
    // really? a 1-to-many for genders
    public Dictionary<int, string> genderTypes { get; set; }

    public EmployeeAddViewModel() { }
    public EmployeeAddViewModel(int id)
    {
        employee = someEntityContext.Employees
            .Where(e => e.ID == id).SingleOrDefault();

        // instantiate your dictionaries

        foreach(var staffType in someEntityContext.StaffTypes)
        {
            staffTypes.Add(staffType.ID, staffType.Type);
        }

        // repeat similar loop for gender types
    }
}

控制器:

[HttpGet]
public ActionResult Add()
{
    return View(new EmployeeAddViewModel());
}

[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
    if(ModelState.IsValid)
    {
        Employee.Add(vm.Employee);
        return View("Index"); // or wherever you go after successful add
    }

    return View(vm);
}

然后,最后在您的视图中(您可以先使用 Visual Studio 为其搭建脚手架),将继承的类型更改为 ShadowVenue.Models.EmployeeAddViewModel.此外,下拉列表所在的位置,请使用:

Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:

@Html.DropDownListFor(model => model.employee.staffTypeID,
    new SelectList(model.staffTypes, "ID", "Type"))

和性别下拉菜单类似

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(model.genderTypes, "ID", "Gender"))

根据评论更新

对于性别,如果您可以在上述建议的视图模型中没有性别类型,您也可以这样做(不过,再想一想,也许我会在视图模型中将此服务器端生成为 IEnumerable).因此,代替下面的 new SelectList...,您将使用 IEnumerable.

For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList... below, you would use your IEnumerable.

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(new SelectList()
    {
        new { ID = 1, Gender = "Male" },
        new { ID = 2, Gender = "Female" }
    }, "ID", "Gender"))

最后,另一个选项是查找表.基本上,您将键值对与查找类型相关联.一个类型的例子可能是性别,而另一个可能是国家等.我喜欢这样构建我的:

Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:

ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1  | Gender     | 1         | Male        | male gender       | 1
2  | State      | 50        | Hawaii      | 50th state        | 1
3  | Gender     | 2         | Female      | female gender     | 1
4  | State      | 49        | Alaska      | 49th state        | 1
5  | OrderType  | 1         | Web         | online order      | 1

当一组数据不经常变化,但仍需要不时枚举时,我喜欢使用这些表.

I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.

希望这有帮助!

这篇关于使用实体框架(.edmx 模型)为 MVC3 创建下拉列表 &amp;剃刀视图&amp;&amp;将一条数据库记录插入多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆