我正在关注这个例子
但是当我提交时,它表示不能将'false'转换为'int'
因为我假设它传递的是假或真,而不是实际值
我做错了什么?
我的模特是
public IEnumerable<AllocateRequirementViewModel> Requirements { get; set; }
public List<int> RequirementIds { get; set; }
然后我的剃刀
<div id="RequirementsContainer">
@foreach (var requirement in Model.Requirements)
{
<div class="row">
<input id="@requirement.Id" type="checkbox" name="RequirementIds" value="@requirement.Id" /> @requirement.Description
</div>
}
</div>
答案 0 :(得分:1)
您的模型需要包含选中的值和所有可能的值。
public class TestViewModel
{
public Guid Id { get; set; }
public IDictionary<Guid, String> AllCheckboxOptions { get; set; }
public Guid[] CheckedOptions { get; set; }
}
我在我的数据库中使用Guids作为PK,因此这些是数据库中的ID
然后我创建了许多扩展方法来生成html
public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, String name, List<SelectListItem> listInfo,
IDictionary<String, Object> htmlAttributes, Int32 columns)
{
if (String.IsNullOrEmpty(name))
throw new ArgumentException("The argument must have a value", "name");
if (listInfo == null)
throw new ArgumentNullException("listInfo");
if (!listInfo.Any())
return new MvcHtmlString(String.Empty);
var outerSb = new StringBuilder();
for (Int32 i = 0; i < columns; i++)
{
var listBuilder = new TagBuilder("ul");
if (columns > 1)
listBuilder.MergeAttribute("class", "column");
var innerSb = new StringBuilder();
var take = listInfo.Count % columns == 0
? listInfo.Count / columns
: (listInfo.Count / columns) + 1;
var items = listInfo.Skip(i * take).Take(take);
foreach (var info in items)
{
var inputBuilder = new TagBuilder("input");
if (info.Selected) inputBuilder.MergeAttribute("checked", "checked");
inputBuilder.MergeAttribute("type", "checkbox");
inputBuilder.MergeAttribute("value", info.Value);
inputBuilder.MergeAttribute("id", info.Value);
inputBuilder.MergeAttribute("name", info.Value);
var labelBuilder = new TagBuilder("label");
labelBuilder.MergeAttribute("for", @info.Value);
labelBuilder.InnerHtml = info.Text;
var listItemWrapper = new TagBuilder("li");
//may have to encode here.
listItemWrapper.InnerHtml = inputBuilder.ToString(TagRenderMode.SelfClosing) + labelBuilder.ToString(TagRenderMode.Normal);
innerSb.Append(listItemWrapper.ToString(TagRenderMode.Normal));
}
listBuilder.InnerHtml = innerSb.ToString();
outerSb.Append(listBuilder.ToString(TagRenderMode.Normal));
}
return new MvcHtmlString(outerSb.ToString());
}
然后在视图中,您可以调用扩展方法
@Html.CheckBoxList("yourtypes", (from o in Model.AllCheckboxOptions
select new SelectListItem
{
Text = o.Value,
Selected = Model.CheckedOptions.Contains(o.Key),
Value = o.Key.ToString()
}).ToList())
我已经成功地将这项技术用于MVC3和MVC4。