【发布时间】:2016-01-08 23:09:11
【问题描述】:
我正在尝试动态创建具有不同类型字段的表单。然后只需将用户输入的数据传回控制器并绑定回我的模型。我为每个控件使用了一个自定义编辑器模板,并希望它能在控制器中正确绑定。但是,该属性每次都是 NULL,所以我无法检索输入值。
型号
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; }
}
查看
@foreach (CustomControlModel ccm in @Model.CustomControlList)
{
if (!string.IsNullOrEmpty(ccm.PropertyName))
{
@Html.EditorFor(model => ccm, "CustomControlModel")
}
}
自定义模板
@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" />
}
任何帮助将不胜感激。提前致谢。
【问题讨论】:
-
它只需要
@Html.EditorFor(m => m.CustomControlList)- 没有foreach循环,假设您在/Views/Shared/EditorTemplates文件夹(或/Views/yourControllerName/EditorTemplates文件夹)中找到了EditorTemplate。但它有点不清楚if (!string.IsNullOrEmpty(ccm.PropertyName))的用途 - 你的模型没有名为PropertyName的属性 -
感谢您的快速回复。这可以很好地让我的控件出现在页面上,但是输入的值没有通过模型绑定器设置。当用户提交表单时,我不能简单地引用模型中的值还是有什么技巧可以获取新值?
-
如果你的POST方法有一个参数
ReceiptModel model那么你提交的时候会正确绑定(包括集合)。如果您遇到问题,那么您需要发布更多代码。 -
@StephenMuecke 我认为问题出在我的自定义编辑器模板中。上面添加的代码。
标签: asp.net-mvc asp.net-mvc-3 model-view-controller