在ASP.NET MVC5中,要在同一视图中编辑父类型和其List<>
类型的子类型,通常会涉及到模型绑定和视图模型的使用。以下是实现这一功能的基础概念和相关步骤:
首先,定义一个包含父类型和子类型列表的视图模型。
public class ParentViewModel
{
public string ParentProperty { get; set; }
public List<ChildViewModel> Children { get; set; }
public ParentViewModel()
{
Children = new List<ChildViewModel>();
}
}
public class ChildViewModel
{
public int Id { get; set; }
public string ChildProperty { get; set; }
}
在视图中,使用Html.EditorFor
辅助方法来渲染父属性和子属性列表。
@model ParentViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.ParentProperty)
<table>
<thead>
<tr>
<th>ID</th>
<th>Child Property</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(m => m.Children)
</tbody>
</table>
<input type="submit" value="Submit" />
}
在Views/Shared
文件夹中创建一个名为EditorTemplates/ChildViewModel.cshtml
的文件,用于渲染每个子项。
@model ChildViewModel
<tr>
<td>@Html.HiddenFor(m => m.Id)</td>
<td>@Html.EditorFor(m => m.ChildProperty)</td>
</tr>
在控制器中,创建一个处理表单提交的方法。
public class YourController : Controller
{
[HttpGet]
public ActionResult Edit()
{
var viewModel = new ParentViewModel();
// 初始化viewModel.Children
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(ParentViewModel viewModel)
{
if (ModelState.IsValid)
{
// 处理数据保存逻辑
return RedirectToAction("Success");
}
return View(viewModel);
}
}
问题:提交表单时,子项的数据没有正确绑定到模型上。
解决方法:确保每个子项都有一个唯一的标识符(如ID),并且在编辑模板中正确使用了Html.HiddenFor
来保持这个标识符。
通过以上步骤,可以在ASP.NET MVC5中有效地在同一视图中编辑父类型和其子类型的列表。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云