我是MVC的新手,并坚持应该是一个非常直接的问题。我正在通过this tutorial并完成所有工作,除了我现在想要添加一个外键'链接'(不确定它叫什么)但似乎无法让它工作。这就是我所拥有的:
表:
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; }
}
查看(Create.cshtml):
...
//What i really want is a dropdown of the values in the Manufactureres table
@Html.EditorFor(model=> model.ManufacturerId)
这在使用关系数据库时必须是一个非常常见的问题,会有很多外键关系要使用/显示,但由于某种原因,我无法在stackoverflow上找到直接对应于这么简单的东西的教程或问题。非常感谢任何指导或方向! 谢谢,
答案 0 :(得分:8)
我希望我能正确理解你的问题。似乎您想要添加新的库存项目,然后您需要下拉列表中的所有制造商的列表。我将继续这个假设,如果我不在赛道上,请告诉我。)
首先去创建一个视图模型。此视图模型将绑定到yout视图。永远不要将域对象绑定到您的视图。
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>
我希望这会有所帮助:)
答案 1 :(得分:2)
是的,这是常见问题,您需要选择Manufactureres
,然后将其发送到视图。您可以使用ViewBag
或strontly类型的视图模型。
<强>示例:
答案 2 :(得分: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)确保“查看”具有以下格式的下拉选择选项
<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