【发布时间】:2022-06-30 19:14:51
【问题描述】:
我的问题是:我无法将数组数据从视图(HTML-select 组件多重模式)传递到存在一对多关系的控制器。
我尝试使用Microsoft.AspNetCore.Mvc.TagHelpers 作为视图。
请看MVC设计(我简化了):
型号
public class Product
{
[Key]
public int id { get; set; }
public string? Name { get; set; }
[ForeignKey("ProductCategory")]
public int Categoryid { get; set; }
public ProductCategory ProductCategory{ get; set; }
}
public class ProductCategory
{
[Key]
public int id { get; set; }
public string Name { get; set; }
public IList<Product> Products{ get; set; }
}
查看
@using Microsoft.EntityFrameworkCore
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model ProjectCategory
<form method="post">
<div class="container-fluid">
<div class="row">
<div class="col-12 col-lg-6 pt-3">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control"/>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="col-12 col-lg-6 pt-3">
<label asp-for="Products"></label><br/>
<select id="Products" asp-for="Accounts" class="form-control" multiple>
<option value="">Please select products...</option>
@{
Context c = new Context();
var products = c.Products.ToList();
}
@foreach(var r in products){<option value="@r.id">@r.Name</option>}
</select>
<span asp-validation-for="Products" class="text-danger"></span>
</div>
<div class="col-12" >
<br/> <button type="submit"> Create</button>
</div>
</div>
</div>
</form>
<script>
// some js code to handle multiple select.. (selectize.js used)
</script>
控制器
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ProductCategory productcategory)
{
if (!ModelState.IsValid)
return View(productcategory);
// Problem is right here.
// in debug mode I see, productcategory.Products Count : 0
// I could not pass Products from the view to controller
Context c = new Context();
c.ProductCategories.Add(productcategory);
c.SaveChanges();
return RedirectToAction("Index");
}
我搜索了,我看到了将多个选择项传递给控制器的示例,但这些示例只是一个数组,没有像我的示例这样一对多传递模型对象的模型。
怎么做?
【问题讨论】:
标签: c# entity-framework-core asp.net-core-mvc html-select asp.net-core-tag-helpers