gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:16:23 26 4
gpt4 key购买 nike

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

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

但是,我发现当我使用 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 事件的 Controller 中读取它。

最佳答案

我个人会为此使用编辑器模板:

<% 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>

现在不仅您的 View 更具可读性,而且编辑器模板会负责为您的隐藏字段生成适当的名称,以便您可以将模型绑定(bind)回去:

[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; }
}

关于c# - ASP.Net MVC 隐藏字段未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5021116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com