问题描述
Create.cshtml
@model Opto.Models.GlassOrder
...
...
...
<div class="text-center" dir="rtl" id="ttt">
</div>
<a id="add1" style="cursor:pointer">add</a>
<script>
var rowNum = 0;
$('#add1').click(function () {
rowNum++;
$.get('/Glasses/displayBill?id=' + rowNum,function (partial) {
console.log(partial);
$('#ttt').append(partial);
});
});
</script>
BillFarSighted.cshtml
@model Opto.Models.BillFarSighted
<div style="display: inline-block">
<div class="row form-group">
<label asp-for="PackFactor" class="col-5 text-left col-form-label"></label>
<div class="col-7">
<select asp-for="PackFactor" class="form-control" asp-items="Html.GetEnumSelectList<Compression>()">
<option selected value="">انتخاب کنید</option>
</select>
<span asp-validation-for="PackFactor" class="text-danger"></span>
</div>
</div>
...
...
...
</div>
BillFarSighted.cs
public partial class BillFarSighted
{
public long Id { get; set; }
public long RecipeId { get; set; }
...
...
...
}
GlassesController.cs
public ActionResult displayBill(int id)
{
BillFarSighted billFarSighted = new BillFarSighted() { PackFactor = 3 };
return PartialView("BillFarSighted",billFarSighted);
}
[HttpPost]
public async Task<IActionResult> Create(List<BillFarSighted> billFarSighteds)
{
....
}
但是当我提交父表单(在create action中)时,billFarSighteds
列表为空,如何在控制器中获取那些局部模型?
解决方法
列出对象绑定的关键是确保将方括号中的顺序索引添加到表单字段的名称属性,例如[0] .PackFactor。
根据您的情况,可以将rowNum用作索引。
Create.csthml
<form asp-action="Create" method="post">
<div class="text-center" dir="rtl" id="ttt">
</div>
<input type="submit" value="submit" class="btn btn-primary" />
</form>
<a id="add1" style="cursor:pointer">add</a>
@section scripts{
<script>
var rowNum = 0;
$('#add1').click(function () {
$.get('/Glasses/DisplayBill?id=' + rowNum,function (partial) {
console.log(partial);
$('#ttt').append(partial);
rowNum++;
});
});
</script>
}
BillFarSighted.cshtml
@model BillFarSighted
<div style="display: inline-block">
<div class="row form-group">
<label asp-for="PackFactor" class="col-5 text-left col-form-label"></label>
<div class="col-7">
<select asp-for="PackFactor" name="[@Model.Id].PackFactor" class="form-control" asp-items="Html.GetEnumSelectList<Compression>()">
<option selected value="">Select</option>
</select>
<span asp-validation-for="PackFactor" class="text-danger"></span>
</div>
</div>
</div>
型号:
public class BillFarSighted
{
public long Id { get; set; }
public long RecipeId { get; set; }
public long PackFactor { get; set; }
}
public enum Compression
{
AAA = 1,BBB = 2,CCC = 3,DDD = 4
}
控制器:
public ActionResult DisplayBill(int id)
{
BillFarSighted billFarSighted = new BillFarSighted() { Id = id };
return PartialView("BillFarSighted",billFarSighted);
}
[HttpPost]
public async Task<IActionResult> Create(List<BillFarSighted> billFarSighteds)
{
//some codes
}
结果: