Reputation: 91
I'm trying to dynamically create a form with different types of fields. Then simply pass the user inputted data back to the controller and bind back to my model. I'm using a custom editor template for each control and was hoping it would bind properly in the controller. However, the property is NULL each time so I cannot retrieve the input values.
Model
public class ReceiptModel : ClassBase
{
public int ReceiptId { get; set; }
public List<CustomControlModel> CustomControlList { get; set; }
}
public class CustomControlModel
{
public string CustomControlName { get; set; }
public CustomControlType CustomControlType { get; set; }
}
View
@foreach (CustomControlModel ccm in @Model.CustomControlList)
{
if (!string.IsNullOrEmpty(ccm.PropertyName))
{
@Html.EditorFor(model => ccm, "CustomControlModel")
}
}
Custom Template
@Html.HiddenFor(model => model.CustomControlId)
<label>@Model.LabelCaption</label>
@switch (@Model.CustomControlType)
{
case CustomControlType.TEXTBOX:
if (@Model.ReadOnly)
{
@Html.TextBoxFor(model => model.CustomControlId, new { @readonly = "readonly", @Value = @Model.Value })
}
else
{
<input id="@Model.CustomControlName" name="@Model.CustomControlName" type="text" value="@Model.Value" />
}
Any help would be much appreciated. Thanks in advance.
Upvotes: 1
Views: 2939
Reputation: 5119
Don't use foreach. It does not result in the correct property names in the rendered html and so the properties will not be picked up by the model binder. Use a for loop instead:
@for (int i = p; I < @Model.CustomControlList.Count; i++)
{
if (!string.IsNullOrEmpty(Model.CustomControlList[i].PropertyName))
{
@Html.EditorFor(model => model.CustomControlList[i], "CustomControlModel")
}
}
Upvotes: 1