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

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

问题描述

阅读100篇关于如何在MVC 3中使用Razor Views创建DropDown列表的文章后,我找不到符合我的情况的文章。所以经过小时和小时的搜索,我决定发布这个问题,看看有没有人有答案或可以帮助我。谢谢你提前!!!



情况:
我最终试图创建一个视图来添加Employee to a Database。



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





目标:


  1. 创建一个Employee(我有Create.cshtml(强类型)与StaffNotify复选框的部分视图){我正在使用单独的@model在通知部分视图从创建视图不知道如果这是安全的? @model ShadowVenue.Models.Employee& @model ShadowVenue.Models.StaffNotify)


  2. 为StaffTypeId创建一个下拉框(将从StaffType表中插入[StaffTypeId]值1到多个关系),但会在下拉列表中显示[Type]字符串值)


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


  4. 将记录插入到数据库中(我在StaffID主键中具有1到1关系的单独表格中的工作人员通知)


我似乎遇到了这个控制器代码的麻烦。



我不知道我是否应该在EDMX模型中创建存储过程,或者提出一些查询或方法语法,不知道哪个是最好的方法。 p>

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



感谢您的时间。我真的很感激这个网站上的知识渊博的用户。



(如果您需要知道任何导航属性名称,以帮助解决方案让我知道,我将提供给您)

解决方案

不要将数据库模型直接传递给您的意见。你很幸运地使用MVC,所以使用视图模型进行封装。



创建一个视图模型类,如下所示:

  public class EmployeeAddViewModel 
{
public Employee employee {get;组; }
public Dictionary< int,string> staffTypes {get;组; }
//真的吗一个1对多的性别
public Dictionary< int,string> genderTypes {get;组;

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

//实例化你的字典

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

//为性别类型重复类似的循环
}
}

控制器:

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

[HttpPost]
public ActionResult添加(EmployeeAddViewModel vm)
{
if(ModelState.IsValid)
{
Employee.Add(vm.Employee);
return View(Index); //或成功后添加
}

return View(vm);
}

然后,最后在你的视图(你可以使用Visual Studio来支架首先),将继承的类型更改为ShadowVenue.Models.EmployeeAddViewModel。另外,在下拉列表中,使用:

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

类似于性别下拉菜单

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

/ strong>



对于性别,如果在上述建议的视图模式中可以不使用genderTypes,那么也可以这样做(尽管如此,第二个想法,也许我会在视图模型中生成此服务器端为IEnumerable)。所以,代替新的SelectList ... ,你将使用你的IEnumerable。

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

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

  ID | LookupType | LookupKey | LookupValue | LookupDescription |活动
1 |性别| 1 |男|男性| | 1
2 |州| 50 |夏威夷第五十州1
3 |性别| 2 |女|女性| 1
4 |州| 49 |阿拉斯加|第49州| 1
5 | OrderType | 1 |网页|在线订单| 1

我喜欢在一组数据不经常变化时使用这些表,但仍然需要不时列举。



希望这有帮助!


After reading 100's of articles on here about how to create a DropDown List in MVC 3 with Razor Views, I could not find one that fit my case. So after Hours and Hours of searching for the answer I have decided to post this question to see if anyone has the answer or can help me out. Thank you in advance!!!

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

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

Objectives:

  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)

  2. 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)

  3. 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)

  4. 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.

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.

This my First Large MVC3 App using Entity Framework Model.

Thank you for your time. I really do appreciate the knowledgeable users on this site.

(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)

解决方案

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
    }
}

Controller:

[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);
}

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"))

and similarly for the gender dropdown

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

Update per comments

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.

Hope this helps!

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

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