I’m not sure if I should use a FormsCollection or something else, with this basic Create view.
(note: I’m using a custom editor template for the Tags ICollection<string>)
Model
public class Question
{
[Required, StringLength(100)]
public string Title { get; set; }
[Required]
public string Body { get; set; }
public ICollection<string> Tags { get; set; }
}
View
@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)
{
... ????
}
or something else?
[HttpPost]
public ActionResult Create(... ??? ...)
{
.... ????
}
Since you have a strongly typed View, you can have your
[HttpPost]method take that same type as the variable, e.g.:The
DefaultModelBinderwill take the values returned, and plug them into your strongly typed model. Viola!As long as the model for your template for your tags collection is of type
string, MVC will iterate through the collection, so that it can be bound (though you may have to change fromICollectionto List).UPDATE
As we discussed in the comments, rather than creating one textbox per tag, create a separate ViewModel which has all of your other Product properties.
Instead of using
List<string> Tagsin your ViewModel, create this property:In your view, have a textbox for
TagCollection. Then, in your Create action, you can parse the TagCollection string into your list of tags.