我是ASP.NET MVC的新手,我试图创建一个页面,其中列出了许多项目,并且还包含一个用于创建新项目的小表格。
所以我创建了这个视图模型:
//The view model has the list of items as AllItems and a member variable for creating a new item.
public class IndexViewModel
{
public List<SListItem> AllItems { get; set; }
//SListItem contains ID, Name and price
public SListItem NewItem { get; set; }
}
在我的剃须刀文件中,添加以下行:
@Html.EditorFor(model => model.NewItem.Name, new { htmlAttributes = new { @class = "form-control"} })
在html输出中,它将创建一个名称设置为“ NewItem.Name”而不是“ Name”的文本输入。
<input name="NewItem.Name" id="NewItem_Name" type="text" value="">
在控制器中,该控制器接收通过表单提交的POST数据
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "ID,Name,ItemType")] ShoppingListItem item)
{
}
当我运行它时,由于表单元素的名称为“ NewItem。*”,因此不会填充“ item”参数。
我该如何克服呢?
提前致谢
最佳答案
对于NewItem
属性使用单独的模型可能会更好。您可以调用@Html.Action()
来呈现NewItem
模型的表单,作为索引视图的子动作。
您的索引视图如下所示:
@model Your.Namespace.IndexViewModel
<div>
<!-- your index markup -->
<!-- call this wherever the child view should render -->
@Html.Action("whatever_you_name_the_action")
</div>
而且您的“编辑”视图看起来像
@model Your.Namespace.SListItem
@Html.EditorFor(m => m.WhateverPropertyOfSListItemYoureAfter)
您只需要确保从子操作中返回
PartialView
而不是View
即可。如果要执行无法直接请求的“特殊”控制器操作,请用ChildActionOnlyAttribute
标记该操作。例如:[ChildActionOnly]
public ActionResult Edit(int? id)
{
return PartialView("_SListItemView");
}