【问题标题】:MVC 5 EditorTemplate for Model renders with same id and name用于模型渲染的 MVC 5 EditorTemplate 具有相同的 ID 和名称
【发布时间】:2016-01-05 21:53:41
【问题描述】:

我有父模型“Receipt”,它具有对象的字典作为一个名为 CustomControlDictionary 的属性,属于 CustomControlModel 类。 在我看来,我遍历CustomControlDictionary 属性中的每个对象并调用EditorTemplate。在模板中,我只需为 CustomControlModel 对象添加标签和文本框。 当代码呈现 html 控件具有相同的 idname 属性: id="key_Value" name="key.Value" 。 我确实尝试使用常规数组或列表而不是字典,但结果相同。期待任何建议。

型号:

public class ReceiptModel 
{
    public ReceiptModel(){}
    public int ReceiptId { get; set; }
    public string ReceiptNumber { get; set; }
    public Dictionary<string, CustomControlModel> CustomControlDictionary{get; set; }
    // public List<CustomControlModel> CustomControlList { get; set; }
}


public class CustomControlModel 
{
    public CustomControlModel(){}
    public int CustomControlId{ get; set; }
    public string CustomControlName{ get; set; }
    public string LabelCaption{ get; set; }
    public string Value{ get; set; }
}   

查看:

//View (@ReceiptModel):
@foreach (var key in Model.CustomControlDictionary )
{
    @Html.EditorFor(m => key.Value,"CustomControlModel")
}

编辑器模板:

@model EWMS_MVC.Classes.CustomControlModel

@Html.HiddenFor(model => model.CustomControlId)
@Html.LabelFor(model => model.CustomControlId, Model.LabelCaption)
@Html.TextBoxFor(model => model.CustomControlId, new { @Value = @Model.Value })

对于ReceiptModelCustomControlDictionary 属性中的所有对象,呈现的html 具有相同的idname

<input id="key_Value_CustomControlId" name="key.Value.CustomControlId" type="hidden" value="201922" />//value here should be "id" of the input field
<label for="key_Value_CustomControlId">Receipt number:</label>
<input id="key_Value_CustomControlId" name="key.Value.CustomControlId" type="text" value="201922" />//value here should be "id" of the input field

【问题讨论】:

    标签: asp.net-mvc editortemplates


    【解决方案1】:

    我认为这种情况的最佳方法是避免模板中的 HtmlHelper 方法,而是使用 html 控件:

    @model EWMS_MVC.Classes.CustomControlModel
    <label>@Model.LabelCaption</label>
    <input id="@Model.CustomControlId" name="@Model.CustomControlName" type="text" value="@Model.Value" />
    

    【讨论】:

    • Steve,我确实切换到了 HTML 控件,它的工作与预期一样。现在,当我提交视图时遇到问题,我的“Reciept”模型的“CustomControlDictionary”属性为空。关于如何确保我从视图中获取值的任何想法?
    • 尝试在模型的构造函数中将其初始化为一个新实例。如果你不需要字符串索引,它可以是一个列表。
    • 我确实更新了我的模型以使用 List 而不是 Dictionary,并且我在 Model 构造函数中初始化了我的 CustomControlModel 列表。 “Reciept”模型类的“CustomControlList”属性仍然为 0 长度。我是否需要在编辑器模板中添加任何内容才能让“Receipt”模型将值存储在“CustomControlList”属性中?
    • 您能发布您的控制器代码和完整视图代码吗?
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2013-05-10
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多