在 ASP.NET Core 3.1 MVC 项目的以下代码中,Get
操作方法Edit (...)
显示邮政编码的下拉列表。似乎默认情况下,下拉列表将列表中的第一个邮政编码(即 1301)显示为所选值。
如果我想在下拉列表中显示从数据库中选择的值,如何在Edit(...)
不创建视图模型的情况下通过操作方法实现它?
我有一个相当复杂的数据模型,其中邮政编码和城市是表 Shop 中的成员,但该表通过连接表 ProductShop 与产品具有多对多关系。我是初学者,所以我一直在尝试遵循本教程,但到目前为止并没有让我受益。https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/update-related-data?view=aspnetcore-5.0
这是我Edit
在控制器中的get方法:
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id) {
if (id == null) {
return NotFound();
}
var product = await _context.Product
.Include(p => p.Brand)
.Include(p => p.Price)
.Include(p => p.ProductCategory)
.ThenInclude(p => p.Category)
.Include(p => p.ProductShop)
.ThenInclude(ps => ps.Shop)
.Include(s => s.ProductShop)
.ThenInclude(ps => ps.Shop)
.ThenInclude(s => s.Zip)
.FirstOrDefaultAsync(m => m.Id == id);
if (product == null) {
return NotFound();
}
ViewData["BrandId"] = new SelectList(_context.Brand, "Id", "BrandName", product.BrandId);
// this is the method where I want to display zipcodes with the help from viewbag
ViewData["ZipId"] = new SelectList(_context.Zipcode.ToList(), "Id", "Zip", product.ProductShop.FirstOrDefault().Shop.Zip.Id);
PopulateSelectedCategories(product);
return View(product);
}
我在视图中的下拉列表:
@model Vegetarian_Products.Models.DB.Product
@*@model Vegetarian_Products.ViewModels.ProductDetailsVM*@
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Product</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
//....
<div class="form-group">
<label asp-for="ProductShop.FirstOrDefault().Shop.Zip.Zip" class="control-label"></label>
<select asp-for="ProductShop.FirstOrDefault().Shop.Zip.Zip" class="form-control" asp-items="ViewBag.ZipId">
</select>
<span asp-validation-for="ProductShop.FirstOrDefault().Shop.Zip.Zip" class="text-danger" />
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a class="btn btn-primary" asp-controller="Products" asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
邮政编码的模型类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Vegetarian_Products.Models.DB {
public partial class Zipcode {
public Zipcode() {
Shop = new HashSet<Shop>();
}
public int Id { get; set; }
[Required(ErrorMessage = "Tilføj postnr")]
[DisplayName("Postnr")]
public int Zip { get; set; }
[DisplayName("By")]
public string City { get; set; }
public virtual ICollection<Shop> Shop { get; set; }
}
}
运行编辑视图的屏幕截图,并且没有从数据库中选择值:
表关系模型: