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 app,这个app有一个基本的表单。我的表单的模型如下:
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"> 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:
当我发布表单时,模型中的记住值总是为false。但是,模型中的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?
我搞不懂。为什么不设置复选框值?
17 个解决方案
#1
177
@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
checkbox
remains unchecked, the form submits only thehidden
value (false) - 如果复选框仍然未选中,表单只提交隐藏值(false)
- If checked, then the form submits two fields (false and true) and MVC sets
true
for the model'sbool
property - 如果选中,则表单提交两个字段(false和true), MVC为模型的bool属性设置true
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
This will always send the default value, if checked.
如果选中,它将始终发送默认值。
#2
63
Since you are using Model.Name to set the value. I assume you are passing an empty view model to the View.
因为你在使用模型。名称以设置值。我假设您正在向视图传递一个空的视图模型。
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
只在选中select框时才传递值。在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\"" : "") />
#3
4
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.
我知道这不是一个优雅的解决方案。希望这里有人能给点建议。
#4
3
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
这会给你一个特别的记忆复选框
#5
3
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.
要将表单中的复选框返回的值转换为布尔属性,我使用了ValueProviderResult在定制的ModelBinder中的build转换器中。
ValueProviderResult cbValue = bindingContext.ValueProvider.GetValue("CheckBoxName");
bool value = (bool)cbValue.ConvertTo(typeof(bool));
#6
2
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:
我遇到了类似的问题,通过使用复选框、隐藏符和小JQuery,我可以得到复选框的值:
@Html.CheckBox("isPreferred", Model.IsPreferred)
@Html.HiddenFor(m => m.IsPreferred)
<script>
$("#isPreferred").change(function () {
$("#IsPreferred").val($("#isPreferred").val());
})
</script>
#7
2
This has been a major pain and feels like it should be simpler. Here's my setup and solution.
这是一个很大的痛苦,感觉应该更简单。这是我的设置和解决方案。
I'm using the following HTML helper:
我正在使用以下HTML助手:
@Html.CheckBoxFor(model => model.ActiveFlag)
@Html。= > model.ActiveFlag CheckBoxFor(模型)
Then, in the controller, I am checking the form collection and processing accordingly:
然后,在控制器中,我正在检查表单的收集和处理:
bool activeFlag = collection["ActiveFlag"] == "false" ? false : true;
[modelObject].ActiveFlag = activeFlag;
#8
2
Use only this
只使用这
$("input[type=checkbox]").change(function () {
if ($(this).prop("checked")) {
$(this).val(true);
} else {
$(this).val(false);
}
});
#9
1
@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);
});
#10
1
For the MVC using Model. Model:
对于使用模型的MVC。模型:
public class UserInfo
{
public string UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
HTML:
HTML:
<input type="checkbox" value="true" id="checkbox1" name="RememberMe" checked="@Model.RememberMe"/>
<label for="checkbox1"></label>
In [HttpPost] function, we can get its properties.
在[HttpPost]函数中,我们可以获得它的属性。
[HttpPost]
public ActionResult Login(UserInfo user)
{
//...
return View(user);
}
#11
0
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 WONT bind 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; }
}
#12
0
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++;
}
#13
0
public ActionResult Index(string username, string password, string rememberMe)
{
if (!string.IsNullOrEmpty(username))
{
bool remember = bool.Parse(rememberMe);
//...
}
return View();
}
#14
0
Modify Remember like this
这样的修改记
public class MyModel
{
public string Name { get; set; }
public bool? Remember { get; set; }
}
Use nullable bool in controller and fallback to false on null like this
在控制器中使用可空的bool,然后在null上回退为false
[HttpPost]
public ActionResult MyAction(MyModel model)
{
model.Remember = model.Remember ?? false;
Console.WriteLine(model.Remember.ToString());
}
#15
0
In my case I was not setting the model property "Remember" in the get method. Check your logic in the controller. You may be doing the same. I hope this help!
在我的例子中,我没有在get方法中设置model属性“Remember”。在控制器中检查逻辑。你可能也在这么做。我希望这帮助!
#16
0
If you really want to use plain HTML (for whatever reason) and not the built-in HtmlHelper extensions, you can do it this way.
如果您真的想使用纯HTML(出于某种原因)而不是内置的HtmlHelper扩展,您可以这样做。
Instead of
而不是
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
try using
试着用
<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked" : "") />
Checkbox inputs in HTML work so that when they're checked, they send the value, and when they're not checked, they don't send anything at all (which will cause ASP.NET MVC to fallback to the default value of the field, false
). Also, the value of the checkbox in HTML can be anything not just true/false, so if you really wanted, you can even use a checkbox for a string field in your model.
复选框输入在HTML中可以工作,当它们被选中时,它们会发送值,当它们没有被选中时,它们不会发送任何东西(这将导致ASP。NET MVC返回到字段的默认值,false)。此外,HTML中的复选框的值可以是任何值,而不仅仅是true/false,因此如果您确实需要,您甚至可以在模型中为字符串字段使用复选框。
If you use the built-in Html.RenderCheckbox
, it actually outputs two inputs: checkbox and a hidden field so that a false value is sent when the checkbox is unchecked (not just nothing). That may cause some unexpected situations, like this:
如果您使用内置的Html。RenderCheckbox实际上输出两个输入:复选框和一个隐藏字段,以便在复选框未选中时发送一个假值(而不是什么都没有)。这可能会导致一些意想不到的情况,比如:
- Why does the CheckBoxFor render an additional input tag, and how can I get the value using the FormCollection?
- 为什么用于呈现附加输入标记的CheckBoxFor,以及如何使用FormCollection获得值?
#17
0
I read through the other answers and wasn't quite getting it to work - so here's the solution I ended up with.
我通读了其他的答案,但并没有把它付诸实践——所以这就是我最终得到的答案。
My form uses the Html.EditorFor(e => e.Property)
to generate the checkbox, and using FormCollection
in the controller, this passes a string value of 'true,false'
in the controller.
我的表单使用Html。为(e => . property)生成复选框,并在控制器中使用FormCollection,在控制器中传递一个字符串值“true,false”。
When I'm handling the results I use a loop to cycle through them - I also use an InfoProperty
instance to represent the current model value being assessed from the form.
当我处理结果时,我使用一个循环遍历它们——我还使用一个InfoProperty实例来表示从表单中评估的当前模型值。
So instead I just check if the string returned starts with the word 'true'
and then set a boolean variable to true
and pass that into the return model.
因此,我只是检查返回的字符串是否以单词“true”开头,然后将布尔变量设置为true并将其传递到返回模型中。
if (KeyName.EndsWith("OnOff"))
{
// set on/off flags value to the model instance
bool keyTrueFalse = false;
if(values[KeyName].StartsWith("true"))
{
keyTrueFalse = true;
}
infoProperty.SetValue(processedInfo, keyTrueFalse);
}
#1
177
@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
checkbox
remains unchecked, the form submits only thehidden
value (false) - 如果复选框仍然未选中,表单只提交隐藏值(false)
- If checked, then the form submits two fields (false and true) and MVC sets
true
for the model'sbool
property - 如果选中,则表单提交两个字段(false和true), MVC为模型的bool属性设置true
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
This will always send the default value, if checked.
如果选中,它将始终发送默认值。
#2
63
Since you are using Model.Name to set the value. I assume you are passing an empty view model to the View.
因为你在使用模型。名称以设置值。我假设您正在向视图传递一个空的视图模型。
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
只在选中select框时才传递值。在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\"" : "") />
#3
4
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.
我知道这不是一个优雅的解决方案。希望这里有人能给点建议。
#4
3
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
这会给你一个特别的记忆复选框
#5
3
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.
要将表单中的复选框返回的值转换为布尔属性,我使用了ValueProviderResult在定制的ModelBinder中的build转换器中。
ValueProviderResult cbValue = bindingContext.ValueProvider.GetValue("CheckBoxName");
bool value = (bool)cbValue.ConvertTo(typeof(bool));
#6
2
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:
我遇到了类似的问题,通过使用复选框、隐藏符和小JQuery,我可以得到复选框的值:
@Html.CheckBox("isPreferred", Model.IsPreferred)
@Html.HiddenFor(m => m.IsPreferred)
<script>
$("#isPreferred").change(function () {
$("#IsPreferred").val($("#isPreferred").val());
})
</script>
#7
2
This has been a major pain and feels like it should be simpler. Here's my setup and solution.
这是一个很大的痛苦,感觉应该更简单。这是我的设置和解决方案。
I'm using the following HTML helper:
我正在使用以下HTML助手:
@Html.CheckBoxFor(model => model.ActiveFlag)
@Html。= > model.ActiveFlag CheckBoxFor(模型)
Then, in the controller, I am checking the form collection and processing accordingly:
然后,在控制器中,我正在检查表单的收集和处理:
bool activeFlag = collection["ActiveFlag"] == "false" ? false : true;
[modelObject].ActiveFlag = activeFlag;
#8
2
Use only this
只使用这
$("input[type=checkbox]").change(function () {
if ($(this).prop("checked")) {
$(this).val(true);
} else {
$(this).val(false);
}
});
#9
1
@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);
});
#10
1
For the MVC using Model. Model:
对于使用模型的MVC。模型:
public class UserInfo
{
public string UserID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
HTML:
HTML:
<input type="checkbox" value="true" id="checkbox1" name="RememberMe" checked="@Model.RememberMe"/>
<label for="checkbox1"></label>
In [HttpPost] function, we can get its properties.
在[HttpPost]函数中,我们可以获得它的属性。
[HttpPost]
public ActionResult Login(UserInfo user)
{
//...
return View(user);
}
#11
0
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 WONT bind 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; }
}
#12
0
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++;
}
#13
0
public ActionResult Index(string username, string password, string rememberMe)
{
if (!string.IsNullOrEmpty(username))
{
bool remember = bool.Parse(rememberMe);
//...
}
return View();
}
#14
0
Modify Remember like this
这样的修改记
public class MyModel
{
public string Name { get; set; }
public bool? Remember { get; set; }
}
Use nullable bool in controller and fallback to false on null like this
在控制器中使用可空的bool,然后在null上回退为false
[HttpPost]
public ActionResult MyAction(MyModel model)
{
model.Remember = model.Remember ?? false;
Console.WriteLine(model.Remember.ToString());
}
#15
0
In my case I was not setting the model property "Remember" in the get method. Check your logic in the controller. You may be doing the same. I hope this help!
在我的例子中,我没有在get方法中设置model属性“Remember”。在控制器中检查逻辑。你可能也在这么做。我希望这帮助!
#16
0
If you really want to use plain HTML (for whatever reason) and not the built-in HtmlHelper extensions, you can do it this way.
如果您真的想使用纯HTML(出于某种原因)而不是内置的HtmlHelper扩展,您可以这样做。
Instead of
而不是
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
try using
试着用
<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked" : "") />
Checkbox inputs in HTML work so that when they're checked, they send the value, and when they're not checked, they don't send anything at all (which will cause ASP.NET MVC to fallback to the default value of the field, false
). Also, the value of the checkbox in HTML can be anything not just true/false, so if you really wanted, you can even use a checkbox for a string field in your model.
复选框输入在HTML中可以工作,当它们被选中时,它们会发送值,当它们没有被选中时,它们不会发送任何东西(这将导致ASP。NET MVC返回到字段的默认值,false)。此外,HTML中的复选框的值可以是任何值,而不仅仅是true/false,因此如果您确实需要,您甚至可以在模型中为字符串字段使用复选框。
If you use the built-in Html.RenderCheckbox
, it actually outputs two inputs: checkbox and a hidden field so that a false value is sent when the checkbox is unchecked (not just nothing). That may cause some unexpected situations, like this:
如果您使用内置的Html。RenderCheckbox实际上输出两个输入:复选框和一个隐藏字段,以便在复选框未选中时发送一个假值(而不是什么都没有)。这可能会导致一些意想不到的情况,比如:
- Why does the CheckBoxFor render an additional input tag, and how can I get the value using the FormCollection?
- 为什么用于呈现附加输入标记的CheckBoxFor,以及如何使用FormCollection获得值?
#17
0
I read through the other answers and wasn't quite getting it to work - so here's the solution I ended up with.
我通读了其他的答案,但并没有把它付诸实践——所以这就是我最终得到的答案。
My form uses the Html.EditorFor(e => e.Property)
to generate the checkbox, and using FormCollection
in the controller, this passes a string value of 'true,false'
in the controller.
我的表单使用Html。为(e => . property)生成复选框,并在控制器中使用FormCollection,在控制器中传递一个字符串值“true,false”。
When I'm handling the results I use a loop to cycle through them - I also use an InfoProperty
instance to represent the current model value being assessed from the form.
当我处理结果时,我使用一个循环遍历它们——我还使用一个InfoProperty实例来表示从表单中评估的当前模型值。
So instead I just check if the string returned starts with the word 'true'
and then set a boolean variable to true
and pass that into the return model.
因此,我只是检查返回的字符串是否以单词“true”开头,然后将布尔变量设置为true并将其传递到返回模型中。
if (KeyName.EndsWith("OnOff"))
{
// set on/off flags value to the model instance
bool keyTrueFalse = false;
if(values[KeyName].StartsWith("true"))
{
keyTrueFalse = true;
}
infoProperty.SetValue(processedInfo, keyTrueFalse);
}