我不确定我是否应该使用 FormsCollection或者别的什么,有了这个基本的 Create查看。
(注意:我使用 custom editor template 作为标签 ICollection<string> )
型号
public class Question
{
[Required, StringLength(100)]
public string Title { get; set; }
[Required]
public string Body { get; set; }
public ICollection<string> Tags { get; set; }
}
查看
@model AWing.Core.Entities.Product
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Question</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Tags)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Tags, "tags")
@Html.ValidationMessageFor(model => model.Tags)
</div>
<p>
<input type="submit" value="Create a new product" />
</p>
</fieldset>
}
Controller
[HttpPost]
public ActionResult Create(FormsCollection formsCollection)
{
... ????
}
还是别的?
[HttpPost]
public ActionResult Create(... ??? ...)
{
.... ????
}
请您参考如下方法:
因为你有一个强类型 View ,你可以有你的 [HttpPost]方法采用与变量相同的类型,例如:
[HttpPost]
public ActionResult Create(Product model)
{
if (ModelState.IsValid)
{
// add new product
.... ????
}
}
DefaultModelBinder将获取返回的值,并将它们插入到您的强类型模型中。中提琴!
只要您的标签集合模板的模型是 string 类型, MVC 将遍历集合,以便可以对其进行绑定(bind)(尽管您可能必须将 ICollection 更改为 List)。
更新
正如我们在评论中讨论的那样,与其为每个标签创建一个文本框,不如创建一个单独的 ViewModel,其中包含所有其他 Product 属性。
而不是使用 List<string> Tags在您的 ViewModel 中,创建此属性:
public string TagCollection { get; set; }
在您看来,有一个 TagCollection 的文本框.然后,在您的创建操作中,您可以将 TagCollection 字符串解析到您的标签列表中。
