【发布时间】:2016-05-29 23:12:09
【问题描述】:
当我的表单中有复选框代码并将其提交给控制器时,仅发送第一个复选框值,而忽略所有其他选中的值。
表单块示例:
@:<input type="checkbox" name="commPref" value="23" />Home Phone
@:<input type="checkbox" name="commPref" value="24" />Cell Phone
@:<input type="checkbox" name="commPref" value="Work" />Work Phone
@:<input type="checkbox" name="commPref" value="26" />Email
@:<input type="checkbox" name="commPref" value="27" />Mail
提交给Controller后:
- 如果检查了手机和电子邮件,“Model.commPref”=“24”-NOT-“24,26”
- 如果选中了工作电话、电子邮件和邮件,则 "Model.commPref" = "Work" -NOT- "Work,26,27"
我对此完全感到困惑。表单复选框周围是否需要额外的代码才能将值组合在一起?在 ColdFusion 中,发回的表单值是检查值的完整字符串。表单控件的“名称”都相同(commPref),因此这应该是该字段的结果值。
编辑:这是模型描述:
[StringLength(255)]
public string commPref { get; set; }
【问题讨论】:
-
commPref的属性类型是什么? (必须是IEnumerable<int>) -
将属性更改为
public IEnumerable<string> commPref { get; set; }(并删除[StringLength]属性。您回发了一个值数组,因此该属性需要是一个数组 -
控制器动作的输入参数是什么。试着让它
string[] commPref -
在尝试了这两种建议后,我在两种情况下都得到了这个错误:
The type 'string[]' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration<TStructuralType>.Property<T>(System.Linq.Expressions.Expression<System.Func<TStructuralType,T>>)'它指向这个上下文 sn-p:modelBuilder.Entity<form_Data>() .Property(e => e.commPref); -
错误提示
commPref是数据模型中的一个属性。在这种情况下,你做这一切都是错的。您需要一个具有属性IEnumerable<string> commPref的视图模型,因为它需要是一个数组才能绑定到您创建的控件。然后您可以使用String.Split()和String.Join()在视图模型之间进行映射,假设数据模型中的commPref是typeofstring(并且您想要一个(比如说)逗号分隔列表)
标签: c# asp.net asp.net-mvc asp.net-mvc-4 checkbox