C# 在 ASP.NET MVC 4 中获取复选框值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14730746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:51:30  来源:igfitidea点击:

Getting Checkbox Value in ASP.NET MVC 4

c#asp.net-mvc-4

提问by JQuery Mobile

I'm working on an ASP.NET MVC 4 app. This app has a basic form. The model for my form looks like the following:

我正在开发一个 ASP.NET MVC 4 应用程序。这个应用程序有一个基本的形式。我的表单模型如下所示:

public class MyModel
{
    public string Name { get; set; }
    public bool Remember { get; set; }
}

In my form, I have the following HTML.

在我的表单中,我有以下 HTML。

<input id="Name" name="Name" type="text" value="@Model.Name" />
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
<label for="Remember">&nbsp;Remember Me?</label>

When I post the form, the Remember value in the model is always false. However, the Name property in the model has a value. I've tested this by setting a breakpoint in the following:

当我发布表单时,模型中的记住值始终为假。但是,模型中的 Name 属性有一个值。我通过在以下设置断点对此进行了测试:

[HttpPost]
public ActionResult MyAction(MyModel model)
{
  Console.WriteLine(model.Remember.ToString());
}

I can't figure it out. Why isn't the Checkbox value getting set?

我想不通。为什么未设置 Checkbox 值?

采纳答案by webdeveloper

@Html.EditorFor(x => x.Remember)

Will generate:

会产生:

<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />

How does it work:

它是如何工作的:

  • If checkboxremains unchecked, the form submits only the hiddenvalue (false)
  • If checked, then the form submits two fields (false and true) and MVC sets truefor the model's boolproperty
  • 如果checkbox未选中,则表单仅提交hidden值 (false)
  • 如果选中,则表单提交两个字段(false 和 true)和true模型bool属性的MVC 集

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

This will always send the default value, if checked.

如果选中,这将始终发送默认值。

回答by Robert

Instead of

代替

 <input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

use:

用:

 @Html.EditorFor(x => x.Remember)

That will give you a checkbox specifically for Remember

这将为您提供一个专门用于记住的复选框

回答by Dan Saltmer

Since you are using Model.Name to set the value. I assume you are passing an empty view model to the View.

由于您使用 Model.Name 来设置值。我假设您将一个空的视图模型传递给视图。

So the value for Remember is false, and sets the value on the checkbox element to false. This means that when you then select the checkbox, you are posting the value "false" with the form. When you don't select it, it doesn't get posted, so the model defaults to false. Which is why you are seeing a false value in both cases.

因此,Remember 的值为false,并将复选框元素上的值设置为false。这意味着当您选择该复选框时,您将在表单中发布值“false”。当您不选择它时,它不会被发布,因此模型默认为 false。这就是为什么您在两种情况下都看到错误值的原因。

The value is only passed when you check the select box. To do a checkbox in Mvc use

该值仅在您选中选择框时传递。在 Mvc 中做一个复选框使用

@Html.CheckBoxFor(x => x.Remember)

or if you don't want to bind the model to the view.

或者如果您不想将模型绑定到视图。

@Html.CheckBox("Remember")

Mvc does some magic with a hidden field to persist values when they are not selected.

Mvc 使用隐藏字段做了一些魔术,以在未选择时保留值。

Edit, if you really have an aversion to doing that and want to generate the element yourself, you could do.

编辑,如果你真的不喜欢这样做并且想要自己生成元素,你可以这样做。

<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked=\"checked\"" : "") />

回答by Yini

Okay, the checkbox is a little bit weird. When you use Html helper, it generates two checkbox inputs on the markup, and both of them get passed in as a name-value pair of IEnumerable if it is checked.

好的,复选框有点奇怪。当您使用 Html helper 时,它会在标记上生成两个复选框输入,如果选中,它们都会作为 IEnumerable 的名称-值对传入。

If it is not checked on the markup, it gets passed in only the hidden input which has value of false.

如果没有在标记上检查它,它只会传入具有 false 值的隐藏输入。

So for example on the markup you have:

例如,在您拥有的标记上:

      @Html.CheckBox("Chbxs") 

And in the controller action (make sure the name matches the checkbox param name on the controller):

在控制器操作中(确保名称与控制器上的复选框参数名称匹配):

      public ActionResult Index(string param1, string param2,
      string param3, IEnumerable<bool> Chbxs)

Then in the controller you can do some stuff like:

然后在控制器中你可以做一些事情,比如:

      if (Chbxs != null && Chbxs.Count() == 2)
        {
            checkBoxOnMarkup = true;
        }
        else
        {
            checkBoxOnMarkup = false;
        }

I know this is not an elegant solution. Hope someone here can give some pointers.

我知道这不是一个优雅的解决方案。希望这里有人可以指点迷津。

回答by Chris

To convert a value returned from a check box in a form to a Boolean property I used the ValueProviderResult's in build converter in a custom ModelBinder.

要将表单中复选框返回的值转换为布尔属性,我在自定义 ModelBinder 中使用了 ValueProviderResult 的构建转换器。

ValueProviderResult cbValue = bindingContext.ValueProvider.GetValue("CheckBoxName");
bool value = (bool)cbValue.ConvertTo(typeof(bool));

回答by John Meyer

I ran into a similar issue and was able to get the checkbox value back by using a checkbox, hiddenfor and little JQuery like so:

我遇到了类似的问题,并且能够通过使用复选框、hiddenfor 和小 JQuery 来获取复选框值,如下所示:

@Html.CheckBox("isPreferred", Model.IsPreferred)
@Html.HiddenFor(m => m.IsPreferred)

<script>

    $("#isPreferred").change(function () {

        $("#IsPreferred").val($("#isPreferred").val());

    })

</script>

回答by Yablargo

I just ran into this (I can't believe it doesn't bind on/off!)

我刚遇到这个(我不敢相信它不会绑定开/关!)

Anyways!

无论如何!

<input type="checkbox" name="checked" />

Will Post a value of "on" or "off".

将发布“on”或“off”值。

This WONTbind to a boolean, but you can do this silly workaround!

不会绑定到一个布尔值,但你可以做这个愚蠢的解决方法!

 public class MyViewModel
 {
     /// <summary>
     /// This is a really dumb hack, because the form post sends "on" / "off"
     /// </summary>                    
     public enum Checkbox
     {
        on = 1,
        off = 0
     }
     public string Name { get; set; }
     public Checkbox Checked { get; set; }
}

回答by Surendran

@Html.EditorFor(x => x.ShowComment)


$(function () {
        // set default value to control on document ready instead of 'on'/'off' 
        $("input[type='checkbox'][name='ShowComment']").val(@Model.ShowComment.ToString().ToLower());
    });

    $("#ShowComment").change(function() {
        // this block sets value to checkbox control for "true" / "false"

        var chkVal = $("input[type='checkbox'][name='ShowComment']").val();
        if (chkVal == 'false') $("input[type='checkbox'][name='ShowComment']").val(true);
        else $("input[type='checkbox'][name='ShowComment']").val(false);

    });

回答by Pascal Carmoni

For multiple checkbox with same name... Code to remove unnecessary false :

对于具有相同名称的多个复选框...删除不必要的错误代码:

List<string> d_taxe1 = new List<string>(Request.Form.GetValues("taxe1"));
d_taxe1 = form_checkbox.RemoveExtraFalseFromCheckbox(d_taxe1);

Function

功能

public class form_checkbox
{

    public static List<string> RemoveExtraFalseFromCheckbox(List<string> val)
    {
        List<string> d_taxe1_list = new List<string>(val);

        int y = 0;

        foreach (string cbox in val)
        {

            if (val[y] == "false")
            {
                if (y > 0)
                {
                    if (val[y - 1] == "true")
                    {
                        d_taxe1_list[y] = "remove";
                    }
                }

            }

            y++;
        }

        val = new List<string>(d_taxe1_list);

        foreach (var del in d_taxe1_list)
            if (del == "remove") val.Remove(del);

        return val;

    }      



}

Use it :

用它 :

int x = 0;
foreach (var detail in d_prix){
factured.taxe1 = (d_taxe1[x] == "true") ? true : false;
x++;
}

回答by Pascal Carmoni

public ActionResult Index(string username, string password, string rememberMe)
{
   if (!string.IsNullOrEmpty(username))
   {
      bool remember = bool.Parse(rememberMe);
      //...
   }
   return View();
}