繁体   English   中英

ASP.Net MVC隐藏字段未按预期工作

[英]ASP.Net MVC Hidden field not working as expected

我可能有一个奇怪的要求,但我认为实施它会很容易。

我将List <>传递给View。 在视图中,我通过列表“预先”,并构建一个表。 在表格中,我需要添加隐藏字段,以便我可以在帖子上获取值。

但是,我发现当我使用Html.Hidden时,该字段不会被渲染。 在视图源中,没有提到字段......

        <table width="600">
        <tr class="headerRow">
            <td>
                Category
            </td>
            <td>
                Sub Category
            </td>
            <td>
                Amount
            </td>
        </tr>
        <% 
            if (Model.TransactionSplitLines != null)
            {
                foreach (var line in Model.TransactionSplitLines)
                {%>

        <tr>
            <td>
                <%=line.Category%>                
                <%=Html.Hidden("CategoryId", line.CategoryId.ToString()) %>

            </td>
            <td>
                <%=line.SubCategory%>
            </td>
            <td>
                <%=line.Amount%>
            </td>
        </tr>
        <%
            }
        } %>
    </table>
</div>
<input type="submit" value="Save" />

当我希望做的是有一个CategoryId数组,我可以在控件上读取Action事件。

我相信这将生成具有相同ID(CategoryID)的多个字段,您是否尝试过不使用Html.Helper并简单地将其替换为:

<input type='hidden' value='<%= line.CategoryId.ToString()%>' />

但是 - 如果您需要通过某种类型的ID获取它们 - 您可以在其中添加一个类并使用jQuery来提取所有值:

<input class='CategoryId' type='hidden' value='<%=line.CategoryId.ToString()%>'/>

然后只需使用$('.CategoryId').each()函数填充列表并将其POST到控制器。

就个人而言,我会使用一个编辑器模板:

<% using (Html.BeginForm()) { %>
    <table width="600">
        <thead>
            <tr class="headerRow">
                <th>Category</th>
                <th>Sub Category</th>
                <th>Amount</th>
            </tr>
        </thead>
        <tbody>
            <%= Html.EditorFor(x => x.TransactionSplitLines) %>
        </tbody>
    </table>
    <input type="submit" value="Save" />
<% } %>

然后有一个相应的编辑器模板( ~/Views/Shared/EditorTemplates/TransactionSplitLine.ascx ):

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Model.TransactionSplitLine>" %>
<tr>
    <td>
        <%= Html.DisplayFor(x => x.Category) %>
        <%= Html.HiddenFor(x => x.CategoryId) %>
    </td>
    <td>
        <%= Html.DisplayFor(x => x.SubCategory) %>
    </td>
    <td>
        <%= Html.DisplayFor(x => x.Amount) %>
    </td>
</tr>

现在不仅您的视图更具可读性,而且编辑器模板将负责为隐藏字段生成专有名称,以便您可以将模型绑定回来:

[HttpPost]
public ActionResult Index(SomeViewModel model)
{
    // TODO: model.TransactionSplitLines should be properly bound 
    // at least the CategoryId property because it's the only one 
    // you are sending in the post
    ...
}

SomeViewModel看起来像这样:

public class SomeViewModel 
{
    public IEnumerable<TransactionSplitLine> TransactionSplitLines { get; set; }
}

和:

public class TransactionSplitLine
{
    public string CategoryId { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM