Aar*_*ron 10 checkbox asp.net-mvc binding state viewmodel
我有一个名为"PropertyFeature"的类,它只包含PropertyFeatureID和Description.它是通过映射到SQL Server数据库表的LINQ to SQL创建的正确模型.示例实例/行将是:
PropertyFeatureID: 2
Description: "Swimming Pool"
Run Code Online (Sandbox Code Playgroud)
行数(PropertyFeatures)当然可以增长和缩小,因此我想动态呈现一个复选框列表,以便用户可以选择其中任何一个.我可以很容易地动态渲染Checkbox,例如:
<%foreach (var Feature in (ViewData["Features"] as IEnumerable<MySolution.Models.PropertyFeature>)) { %>
<%=Html.CheckBox("Features", new { @id = Feature.PropertyFeatureID, @value = Feature.PropertyFeatureID })%><label for="Feature<%=Feature.PropertyFeatureID%>"><%=Feature.Description%></label>
<%}%>
Run Code Online (Sandbox Code Playgroud)
我为每个复选框指定ID并呈现匹配的标签,以便用户可以直观地单击标签并切换复选框 - 这很有效.
我将CheckBox的"名称"设置为"Features",因此所有复选框都以相同的名称呈现,并且MVC Model Binder在发布表单时将它们堆叠到一个名为"Features"的集合中.这很好用.
提交表单后,我使用选中的值并存储它们,因此我需要实际的整数值,因此我知道选择了哪个PropertyFeature,而不仅仅是一堆布尔值和字段名称.理想情况下,我希望它可以作为一个易于使用的数组或集合.
单击按钮时,我可以从Controller方法中检索所选值,因为我已将参数指定为int [] Features.
但问题是它没有维持状态.也就是说,当我单击提交按钮并重新加载页面(再次显示该表单)时,我希望所有动态复选框保持其已检查状态(或不保持).所有这一切我已经创造了其他领域Html.DropDownList
,并Html.TextBox
都保持自己的状态没有任何成功都在同一页上以相同的形式问题.
我花了几个小时阅读关于类似问题的所有其他线程和文章,并且有很多关于使用ICollection
和IDictionary
捆绑的内容,并为每个项目包含一个布尔值,以便它可以保持复选框状态.但我并没有100%掌握如何在我个人的例子中使用它.我想保持解决方案非常简单,不必为了保持我的复选框状态而编写新类的页面.
这样做最干净,最恰当的方法是什么?
Aar*_*ron 15
经过各种不同的方法,我开始工作了.
在视图中:
<%string[] PostFeatures = Request.Form.GetValues("Features");%>
<% foreach (var Feature in (ViewData["AllPropertyFeatures"] as
IEnumerable<MySolution.Models.PropertyFeature>))
{ %>
<input type="checkbox" name="Features"
id="Feature<%=Feature.PropertyFeatureID.ToString()%>"
value="<%=Feature.PropertyFeatureID%>"
<%if(PostFeatures!=null)
{
if(PostFeatures.Contains(Feature.PropertyFeatureID.ToString()))
{
Response.Write("checked=\"checked\"");
}
}
%> />
<label for="Feature<%=Feature.PropertyFeatureID%>">
<%=Feature.Description%></label> <%
} %>
Run Code Online (Sandbox Code Playgroud)
在接收控制器方法中:
public ActionResult SearchResults(int[] Features)
Run Code Online (Sandbox Code Playgroud)
这种方法有许多优点:
对于想要动态复选框列表的最干净/无膨胀解决方案的人,我会推荐这种方法,您需要这些ID,而您只想开展业务!
归档时间: |
|
查看次数: |
12677 次 |
最近记录: |