我有一个问题列表模型,类型为布尔,字符串和对象。 每当我选择任何响应时,它都必须将值绑定到模型,并且在提交表单时,它必须发布值。
型号.cs
public enum QuestionType
{
bool,
list,
YesorNo
}
public class Question
{
public string Id{ get; set; }
public QuestionType Type{ get; set; }
public object ResponseValue{ get; set; }
public List<Option> Option { get; set; }
}
当问题类型为列表时,列表选项将具有列表选项。下面是选项模型
public class Option
{
public int Id{ get; set; }
public string name{ get; set; }
public bool selected{ get; set; }
}
因此,每当我给出以下问题的答案时
- BOOL 类型,则值应绑定为 True 或 False 到响应值
- LIST类型,然后它必须获取所有选定的选项以及Id和名称,并将其作为对象绑定到ResponseValue。
- YesorNo 则值应绑定为"是"、"否"或"否"到响应值
我正在使用 C# 剃须刀视图进行模型绑定
@Html.CheckBoxFor(m => Model.ResponseValue, new { @class = "form-control" })
上面的代码由于其数据类型对象而引发错误,但复选框仅接受布尔数据类型。
请建议如何使响应值接受所有数据类型(布尔值,字符串和对象(
如果你能想出一个不使用object
的设计,可能会更好,但如果没有其他方法,你可以使用如下方法让它工作:
将变量强制转换为相应的类型:
@{
bool? responseValueBool = Model.ResponseValue as bool?;
}
在 HTML 帮助程序的调用中使用新变量:
@if (responseValueBool.HasValue)
{
var ResponseValue = responseValueBool.Value;
@Html.CheckBoxFor(m => ResponseValue, new {@class = "form-control"});
}
编辑:要将索引包含在元素名称中,您可以将ResponseValues
放入列表中,以便能够以m => ResponseValue[index]
的形式按预期传递元素,如文档中所示,例如:
var ResponseValue = new List<bool> {responseValueBool.Value};
@Html.CheckBoxFor(m => ResponseValue[0], new {@class = "form-control", name="ResponseValue[1]"});
不过,您需要注意使用连续索引。 请注意,您不会被迫使用 HTML 帮助程序,也可以自己创建 HTML 元素以避免此类解决方法。