问题是当我尝试同时更新主表和详细信息表时 当调用Post Edit Task时,不会出现Details对象。
编辑视图正确显示所有详细信息行,但在调试编辑POST时,Casas为空
模特
public partial class Modelo : IValidatableObject {
public Modelo()
{
Casas = new HashSet<Casa>();
}
public int Modeloid { get; set; }
public string Modelo1 { get; set; }
public virtual ICollection<Casa> Casas { get; set; }//Don’t work to update
}
public partial class Casa // DETAIL TABLE
{
public int Casaid { get; set; }
public int Modeloid { get; set; } // FK to Modelo
public string Casa1 { get; set; }
public virtual Modelo Modelo { get; set; }
}
CONTROLLER
public class ModelosController : Controller
. . . . . . . . .
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, Modelo modelo)
{
if (id != modelo.Modeloid)
{
return NotFound();
}
if (ModelState.IsValid)
{
// Here modelo.Modelo1 has current modified value
// but modelo.Casas.Count == 0
_context.Update(modelo);
await _context.SaveChangesAsync();
}
}
// GET: Modelos/Edit
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var modelo = await _context.Modelo
.AsNoTracking()
.Include(m => m.Fotomodelos)
.Include(m => m.Casas)
.SingleOrDefaultAsync(m => m.Modeloid == id);
if (modelo == null)
{
return NotFound();
}
return View(modelo);
}
查看EDIT.CSHTML
@using System.IO
@model Disponibilidad.Models.Modelo
<form asp-action="Edit">
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Modeloid" />
<div class="form-group">
<label asp-for="Modelo1" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Modelo1" class="form-control" />
<span asp-validation-for="Modelo1" class="text-danger"></span>
</div>
</div>
@{
for (int i = 0; i < Model.Casas.Count; i++)
{
<input type="hidden" asp-for="@Model.Casas.ElementAt(i).Modeloid"
value="@Model.Modeloid" />
<input type="hidden" asp-for="@Model.Casas.ElementAt(i).Casaid" />
<div class="form-group">
<label asp-for="@Model.Casas.ElementAt(i).Casa1"
class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="@Model.Casas.ElementAt(i).Casa1"
class="form-control" /> <!-- DISPLAY OK Detail rows -->
<span asp-validation-for="@Model.Casas.ElementAt(i).Casa1"
class="text-danger"></span>
</div>
</div>
}
}
<div class="btn-group">
<button type="submit" class="btn btn-danger">Save</button>
</div>
</div>
</form>
答案 0 :(得分:0)
在Razor中使用for
周期而不是foreach
时,使用默认的asp-for
TagHelper时,属性的名称无法正确呈现。
您可以更改剃刀格式输入的示例,如下所示:
自:
<input type="hidden" asp-for="@Model.Casas.ElementAt(i).Casaid" />
要:
<input type="hidden" name="modelo.Casas[@i].Casaid" value="@Model.Casas.ElementAt(i).Casaid" />