Skip to main content
 首页 » 编程设计

c#之在 ASP.NET MVC 中,仅为 View 模型的一个成员创建表单

2024年02月13日11lhb25

我是 ASP.NET MVC 的新手,我正在尝试创建一个页面,其中列出了一些项目,还包含一个用于创建新项目的小表单。 所以我创建了这个 View 模型:

//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; } 
} 

在我的 razor 文件中,我添加了一行:

@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=""> 

在 Controller 中,接收通过表单提交的 POST 数据

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Index([Bind(Include = "ID,Name,ItemType")] ShoppingListItem item) 
{ 
} 

当我运行它时,“item”参数没有被填充,因为表单元素的名称为“NewItem.*”

我该如何克服这个问题?

提前致谢

请您参考如下方法:

您最好为 NewItem 属性使用单独的模型。您可以调用 @Html.Action() 将 NewItem 模型的表单呈现为索引 View 的子操作。

您的索引 View 将如下所示:

@model Your.Namespace.IndexViewModel 
 
<div> 
    <!-- your index markup --> 
 
    <!-- call this wherever the child view should render --> 
    @Html.Action("whatever_you_name_the_action") 
</div> 

你的“编辑” View 看起来像

@model Your.Namespace.SListItem  
 
@Html.EditorFor(m => m.WhateverPropertyOfSListItemYoureAfter) 

您只需要确保从子操作返回 PartialView 而不是 View。如果您想要一个无法直接请求的“特殊” Controller 操作,请使用 ChildActionOnlyAttribute 标记该操作。例如:

[ChildActionOnly] 
public ActionResult Edit(int? id) 
{ 
    return PartialView("_SListItemView"); 
}