【问题标题】:MVC Dropdown Menu using Linked Tables使用链接表的 MVC 下拉菜单
【发布时间】:2017-09-29 00:18:53
【问题描述】:

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

【问题讨论】:

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


【解决方案1】:

首先,创建表格:

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

【讨论】:

    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多