4

我是 MVC 的新手,并且坚持应该是一个非常直截了当的问题。我正在学习本教程,一切正常,除了我现在想添加一个外键“链接”(不知道它叫什么),但似乎无法让它工作。这是我所拥有的:

表:

 Inventory:
 Id   |  SerialNumber  | ManufacturerId (foreignkey to Manufactueres->id)

 Manufactureres
 Id (primary key)   |  Name

型号(InventoryItem.cs):

 public class InventoryItem {
     public int Id {get; set; }
     public int SerialNumber{ get; set; }

     //this starts the trouble, I actually want to interact with the Manufactureres table -> Name column
     public int ManufacturerId { get; set; }  
 }

查看(创建.cshtml):

 ...
 //What i really want is a dropdown of the values in the Manufactureres table
 @Html.EditorFor(model=> model.ManufacturerId)

当使用关系数据库时,这一定是一个非常普遍的问题,会有许多外键关系要使用/显示,但由于某种原因,我在 stackoverflow 上找不到与如此简单的事情直接对应的教程或问题。非常感谢任何指导或方向!谢谢,

4

3 回答 3

9

我希望我能正确理解你的问题。似乎当您想要添加新的库存项目时,您想要在下拉列表中列出所有制造商。我将在这个假设上工作,如果我偏离了轨道,请告诉我:)

首先去创建一个视图模型。您将绑定到您的视图的此视图模型。永远不要将域对象绑定到您的视图。

public class InventoryItemViewModel
{
     public int SerialNumber { get; set; }

     public int ManufacturerId { get; set; }

     public IEnumerable<Manufacturer> Manufacturers { get; set; }
}

您的域对象:

public class InventoryItem
{
     public int Id { get; set; }

     public int SerialNumber{ get; set; }

     public int ManufacturerId { get; set; }
}

public class Manufacturer
{
     public int Id { get; set; }

     public string Name { get; set; }
}

您的控制器可能如下所示:

public class InventoryItemController : Controller
{
     private readonly IManufacturerRepository manufacturerRepository;
     private readonly IInventoryItemRepository inventoryItemRepository;

     public InventoryItem(IManufacturerRepository manufacturerRepository, IManufacturerRepository manufacturerRepository)
     {
          // Check that manufacturerRepository and inventoryItem are not null

          this.manufacturerRepository = manufacturerRepository;
          this.inventoryItemRepository = inventoryItemRepository;
     }

     public ActionResult Create()
     {
          InventoryItemViewModel viewModel = new InventoryItemViewModel
          {
               Manufacturers = manufacturerRepository.GetAll()
          };

          return View(viewModel);
     }

     [HttpPost]
     public ActionResult Create(InventoryItemViewModel viewModel)
     {
          // Check that viewModel is not null

          if (!ModelState.IsValid)
          {
               Manufacturers = manufacturerRepository.GetAll()

               return View(viewModel);
          }

          // All validation is cool

          // Use a mapping tool like AutoMapper
          // to map between view model and domain model
          InventoryItem inventoryItem = Mapper.Map<InventoryItem>(viewModel);

          inventoryItemRepository.Insert(inventoryItem);

          // Return to which ever view you need to display
          return View("List");
     }
}

然后在您看来,您可能会遇到以下情况:

@model MyProject.DomainModel.ViewModels.InventoryItems.InventoryItemViewModel

<table>
     <tr>
          <td class="edit-label">Serial Number <span class="required">**</span></td>
          <td>@Html.TextBoxFor(x => x.SerialNumber, new { maxlength = "10" })
              @Html.ValidationMessageFor(x => x.SerialNumber)
          </td>
     </tr>
     <tr>
          <td class="edit-label">Manufacturer <span class="required">**</span></td>
          <td>
               @Html.DropDownListFor(
                    x => x.ManufacturerId,
                    new SelectList(Model.Manufacturers, "Id", "Name", Model.ManufacturerId),
                    "-- Select --"
               )
               @Html.ValidationMessageFor(x => x.ManufacturerId)
          </td>
     </tr>
</table>

我希望这有帮助 :)

于 2012-09-21T08:26:16.260 回答
2

是的,这是常见问题,您需要Manufactureres在操作中选择,然后将它们发送到查看。您可以使用ViewBag或强类型视图模型。

例子:

于 2012-09-20T19:42:06.047 回答
0

这就是我向你推荐的。

1)创建制造商模型类

public class Manufacturer
{
     public int Id { get; set; }

     public string Name { get; set; }
}

2)创建InventoryItem模型类如下

public class InventoryItem
{
     public int Id { get; set; }

     public int SerialNumber{ get; set; }

     public int ManufacturerId { get; set; }

[ForeignKey("Id ")]
public Manufacturer Manufacturer{get; set;}

public IEnumerable<Manufacturer> Manufacturer {get;set;}

}

3) 确保 DbContext 也更新如下

public DbSet<InventoryItem> InventoryItem {get;set;}
public DbSet<Manufacturer> Manufacturer{get;set;}

4) 控制器

[HttpGet]
        public ActionResult Create()
        {
            InventoryItem model = new InventoryItem();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model.Manufacturer= new SelectList(db.Manufacturer.ToList(), "Id", "Name");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(InventoryItem  model)
        {
            //Check the Model State
            if(! ModelState.IsValid)
            {
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    model.Manufacturer= new SelectList(db.Manufacturer.ToList(), "Id", "Name");
                    return View(model);
                }
            }

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                InventoryItem  dto = new InventoryItem();
                dto.SerialNumber= model.SerialNumber;
                dto.Id= model.Id;

                Manufacturer manudto = db.Manufacturer.FirstOrDefault(x => x.Id== model.Id);
                dto.CatName = manudto.CatName;

                db.Test.Add(dto);
                db.SaveChanges();
            }
                TempData["SM"] = "Added";

                return RedirectToAction("Index");
        }

5) 确保 View 具有以下格式的下拉选择选项

<div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Id, Model.Manufacturer,"Select", new { @class = "form-control" } )
                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
            </div>
        </div>

希望这有效:D

于 2020-05-28T09:00:33.180 回答