获取复选框的值从在的FormCollection asp.net的MVC [英] Getting values of check-box from formcollection in asp.net mvc

查看:1640
本文介绍了获取复选框的值从在的FormCollection asp.net的MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看有的题目在这里,但我仍然有从复选框获得值的问题。

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

模式的一部分:

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

查看的部分:

    <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>

控制器部分:

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

和问题是我不明白TargetLanguages​​任何痕迹在我的FormCollection。我试图CheckBoxFor但它不能帮助。我试着写复选框手动也。

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.

编辑:好吧,我只注意到问题出在哪里了。我有搞砸了标记,这就是为什么我不能从的FormCollection获取数据的原因。

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.

推荐答案

创建所有具有相同名称的复选框。在此示例中,我使用SelectedTargetLanguages​​。

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).

您应该使用明确的参数,像这样,而不是普通的的FormCollection 。无论如何,如果你使用的FormCollection,您shpuld也收到数组。

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

这篇关于获取复选框的值从在的FormCollection asp.net的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆