使用链接表的MVC下拉菜单

时间:2017-05-01 15:21:59

标签: html asp.net-mvc asp.net-mvc-4 drop-down-menu entity-framework-6

我对MVC很新,还在努力学习。我现在已经研究了几个小时,但没有找到我要找的东西。我所拥有的是两个链接表table1和table2。让我们说table2包含/显示来自table1的ID,而不是我希望显示链接到ID的值,例如:名称,而不是我的视图在创建或详细信息时的值,但是在编辑或创建,我希望显示一个下拉菜单供用户选择名称。就像我说我已经研究了很长一段时间而无法找到答案。不幸的是,我没有代码可以显示,但是正确方向的提示将非常有用。

1 个答案:

答案 0 :(得分:0)

首先,创建表格:

--instead of Breaz, use your database name
USE [Breaz]
GO
/****** Object:  Table [dbo].[table1]    Script Date: 5/1/2017 10:11:40 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[table1](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](20) NULL,
 CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[table2]    Script Date: 5/1/2017 10:11:40 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[table2](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [table1Id] [int] NULL,
    [table2Desc] [varchar](20) NULL,
 CONSTRAINT [PK_table2] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[table1] ON 

GO
INSERT [dbo].[table1] ([Id], [name]) VALUES (1, N'ddl1')
GO
INSERT [dbo].[table1] ([Id], [name]) VALUES (2, N'ddl2')
GO
INSERT [dbo].[table1] ([Id], [name]) VALUES (3, N'ddl3')
GO
SET IDENTITY_INSERT [dbo].[table1] OFF
GO
SET IDENTITY_INSERT [dbo].[table2] ON 

GO
INSERT [dbo].[table2] ([Id], [table1Id], [table2Desc]) VALUES (1, 1, N'select1')
GO
INSERT [dbo].[table2] ([Id], [table1Id], [table2Desc]) VALUES (2, 2, N'select2')
GO
SET IDENTITY_INSERT [dbo].[table2] OFF
GO
ALTER TABLE [dbo].[table2]  WITH CHECK ADD  CONSTRAINT [FK_table2_table1] FOREIGN KEY([table1Id])
REFERENCES [dbo].[table1] ([Id])
GO
ALTER TABLE [dbo].[table2] CHECK CONSTRAINT [FK_table2_table1]
GO

创建一个EDMX文件,如下所示:

右键单击Models文件夹,然后单击Add-> ADO.DATA ENTITY MODEL,将其命名为aDropDown。点击确定。突出显示已从数据库生成,单击下一步。单击“新建连接...”将服务器名称放在服务器名称框中。我用。\ sqlexpress。如果您使用用户名和密码,请单击“使用Windows身份验证”,然后输入您的凭据并单击“保存我的密码”。从下拉列表中选择您的数据库名称。点击没关系。如果您输入了密码,请等到您可以回答Y,包括敏感信息。将“保存实体连接设置...”下的名称复制到剪贴板。单击“下一步”。展开Tables,检查table1和table2,然后单击Finish。单击“确定”两次以显示出现的窗口。关闭图表。

这是您的控制器/视图:

public class DDLModel
{
    public DDLModel()
    {
        List<SelectListItem> list = new List<SelectListItem>();

        try
        {
            //BreazEntities16 for you should be the item that you had copied to the clipboard
            //before, or check the aDropDown.Context.cs file
            using (BreazEntities16 entity = new BreazEntities16())
            {
                entity.table1.
                    OrderBy(r => r.name).ToList().ForEach(r => list.Add(
                    new SelectListItem { Text = r.name, Value = r.Id.ToString() }));
            }
        }
        catch (Exception e)
        { }

        //add <select> to first item
        list.Insert(0, new SelectListItem { Text = "", Value = "" });
        Table1List = list;
    }

    public List<SelectListItem> Table1List { get; set; }

    //If you want to put [Required] or other attributes into your model property, and
    //you think you don't want to directly use table2, please use DO use the direct table2,
    //Just see the following post
    //http://stackoverflow.com/questions/14059455/adding-validation-attributes-with-an-entity-framework-data-model
    public table2 table2 { get; set; }
}

public class HomeController : Controller
{
    //I use Index60, you should use Index or what the RouteConfig points to
    [HttpPost]
    public ActionResult Index60(DDLModel ddlModel)
    {
        //BreazEntities16 for you should be the item that you had copied to the clipboard
        //before, or check the aDropDown.Context.cs file
        using (BreazEntities16 entity = new BreazEntities16())
        {
            //modify the tableId of table2
            entity.table2.Attach(ddlModel.table2);
            entity.Entry(ddlModel.table2).Property(x => x.table1Id).IsModified = true;
            entity.Configuration.ValidateOnSaveEnabled = false;
            entity.SaveChanges();  //tableid changes, not table2Desc
        }

        return View(ddlModel);
    }

    //I use Index60, you should use Index or what the RouteConfig points to
    public ActionResult Index60()
    {
        DDLModel ddlModel = new DDLModel();

        //BreazEntities16 for you should be the item that you had copied to the clipboard
        //before, or check the aDropDown.Context.cs file
        using (BreazEntities16 entity = new BreazEntities16())
        {
            //make sure there is using System.Data.Entity at top
            //I am getting first but you can .Where to find another 
            ddlModel.table2 = entity.table2.Include(q => q.table1).Where(r => r.Id == 1).FirstOrDefault();
        }

        return View(ddlModel);
    }

以下是您的观点:

@model Testy20161006.Controllers.DDLModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index60</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        <div>
            <table>
                <tr>
                    <td>
                        @*need the hidden id*@
                        @Html.HiddenFor(r=>r.table2.Id)

                        @Html.LabelFor(r => r.table2.table1Id)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.table2.table1Id,
                    new SelectList(Model.Table1List, "Value", "Text"))
                        @Html.ValidationMessageFor(model => model.table2.table1Id)
                    </td>
                </tr>
            </table>
        </div>
        <input type="submit" value="submit" />
    }
</body>
</html>