This is my model:
public class Attribute
{
public string Key { get; set; }
public string Value{ get; set; }
}
I fill it in my GET create
public ActionResult Create()
{
var Attributes = new[]
{
new Attribute {Key = "Name" Value = "" },
new Attribute {Key = "Age" Value = "" },
};
return View(Attributes);
}
My View looks like this:
@model IEnumerable<Customers.ViewModels.Attribute>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
@foreach (var item in Model)
{
<div class="editor-label">
@Html.Label(item.Key)
</div>
<div class="editor-field">
@Html.EditorFor(m => item.Value)
@Html.ValidationMessageFor(m => item.Value)
</div>
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Then My Post Create looks like this:
[HttpPost]
public ActionResult Create(IEnumerable<Attribute> attributes)
{
}
but my IEnumerable<Attribute> attributes
is null. Any suggestions?
You need to create a editor template for a Attribute
and then pass the List<Attribute>
model to it.
@Model Attribute
<div class="editor-label">
@Html.LabelFor(m => m.Key)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.Value)
@Html.ValidationMessageFor(m => item.Value)
</div>
In your view use:
<fieldset>
@Html.EditorFor(m > m)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
You need to do this because the foreach
doesn't create the correct name for the elements.