0

Ich bin ziemlich neu in MVC und immer noch versuchen zu lernen. Ich recherchiere seit ein paar Stunden und habe nicht gefunden, wonach ich suche. Was ich habe, ist zwei verknüpfte Tabellen, Tabelle1 und Tabelle2. Angenommen, Tabelle2 enthält/zeigt die ID aus Tabelle1 an und statt dessen möchte ich den mit der ID verknüpften Wert anzeigen, z. B. den Namen anstelle des Werts, wenn meine Ansichten in create oder details sind, aber beim Bearbeiten oder Erstellen, Ich möchte ein Dropdown-Menü anzeigen, in dem der Benutzer den Namen auswählen kann. Wie ich schon sagte, habe ich eine ganze Weile recherchiert und konnte keine Antwort finden. Ich habe leider keinen Code zu zeigen, aber ein Hinweis in die richtige Richtung wäre sehr hilfreich.MVC Dropdown-Menü mit verknüpften Tabellen

+0

Vorausgesetzt, dass Sie Ihre Entity Framework Modelle richtig konfiguriert haben, werfen Sie einen Blick auf die [mvc dropdownlistfor] (https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet- mvc). –

Antwort

0

Erstellen Sie zunächst Ihre Tabellen:

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

Neues EDMX wie so Datei:

Rechtsklick auf den Models Ordner und klicken Sie auf Add-> ADO.DATA Entitätsmodell, Name es aDropDown. OK klicken. Wenn die Option Aus Datenbank generieren markiert ist, klicken Sie auf Weiter. Klicken Sie auf Neue Verbindung ... Geben Sie Ihren Servernamen in das Feld für den Servernamen ein. Ich benutze. \ Sqlexpress. Wenn Sie den Benutzernamen und das Passwort verwenden, klicken Sie auf Windows Auth verwenden, geben Sie Ihre Zugangsdaten ein und klicken Sie auf Save my password. Wählen Sie Ihren Datenbanknamen aus dem Dropdown-Menü aus. Klicken Sie auf OK. Wenn Sie ein Passwort eingegeben haben, warten Sie, bis Sie Y beantworten können, und fügen Sie die sensible Datei hinzu. Kopieren Sie den Namen in der Zwischenablage unter 'Entity connection setting speichern ...' Klicken Sie auf Weiter. Erweitern Sie Tabellen, und überprüfen Sie Tabelle1 und Tabelle2, und klicken Sie auf Fertig stellen. Klicken Sie zweimal auf OK, um die Fenster zu öffnen. Schließen Sie das Diagramm.

Hier ist der Controller/Ansicht:

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

hier Ihre Ansicht ist:

@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> 
Verwandte Themen