Getting values of check-box from formcollection in asp.net mvc

I viewed some topics here but I still have a problem with getting values from checkboxes.

Part of Model :

public Dictionary<Language, bool> TargetLanguages { get; set; }

Part of View :

    <div class="editor-label">
        <label for="TargetLanguages">select target languages</label>
    </div>
    <div class="editor-field">
        <form>
            @foreach (var item in Model.TargetLanguages)
            {                    
                @Html.CheckBox("TargetLanguages["+item.Key.Name+"]", item.Value)
                @item.Key.Name
            }
        </form>
    </div>

Part of Controller :

    [HttpPost, ActionName("AddDictionary")]
    public ActionResult AddDictionary(FormCollection collection)
    {
     ...
    }

And the problem is I don’t get any trace of TargetLanguages in my FormCollection. I tried CheckBoxFor but it wasn’t help. I tried write check-box manually also.

EDITED : Okay, I just noticed where the problem was. I’ve got messed up markers and that was the reason why I can’t get data from FormCollection.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Create all the checkboxes with the same name. In this sample I’m using ‘SelectedTargetLanguages’.

@using (Html.BeginForm())
{
    foreach (var item in Model.TargetLanguages)
    {
        <label>
            @Html.CheckBoxFor(m => m.SelectedTargetLanguages, item.value)
            @item.KeyName
        </label>
    }
    <br/>
    @Html.SubmitButton("Actualizar listado")
}

Then, in your action the parameter must be an array of strings like this:

public ActionResult AddDictionary(string[] selectedTargetLanguages)

Note that the name of the argument is the same name of the checkboxes. (It works even with the different casing).

You should use explicit arguments like this, rather than the generic FormCollection. Anyway, if you use FormCollection, you shpuld also receive the array.

Method 2

I have asked same type of question previously. Please check the following links

MVC3 @Html.RadioButtonfor Pass data from view to controller

MVC3 @html.radiobuttonfor

I think this might helps you.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x