Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c# - How to bind checkbox values to a list of ints?

I am following this example

enter link description here

But when I submit, it says can't convert 'false' to 'int'

as I assume its the false or true that is getting passed, not the actual value

what am I doing wrong?

My model is

  public IEnumerable<AllocateRequirementViewModel> Requirements { get; set; }

  public List<int> RequirementIds { get; set; }

then my razor is

  <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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

your model is going to need to contain both the checked values and all the possible values.

public class TestViewModel
{
    public Guid Id { get; set; }
    public IDictionary<Guid, String> AllCheckboxOptions { get; set; }
    public Guid[] CheckedOptions { get; set; }
}

I use Guids as PKs in my database so these are the IDs from the database

I then created a number of extension methods to generate the 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());
    }

then in the view you can call your extension method

    @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())

I've used this technique with both MVC3 and MVC4 with success.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...