MVC 4 EditorFor布尔复选框总是发布真 [英] MVC 4 EditorFor bool Checkbox always posting True

查看:93
本文介绍了MVC 4 EditorFor布尔复选框总是发布真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模型中的布尔属性。渲染视图时它的值是假的。但是,当我提交表单,TRUE值被传递到控制器。我使用的是自定义的js函数来从表单中的值提交到一个控制器的动作。我不知道如何从复选框正确的值。

I have a bool property in my model. Its value is false when rendering the view. But when I submit the form, the value of TRUE is being passed to the controller. I am using a custom js function to get the values from the form to submit to a controller action. I am not sure how to get the correct value from the checkbox.

我的模型属性:

public bool RushOrderFlag { get; set; }

该视图标记:

@Html.EditorFor(model => model.RushOrderFlag)

呈现的HTML:

The HTML Rendered:

<input class="chkbx" data-val="true" data-val-required="The Rush? field is required." id="RushOrderFlag" name="RushOrderFlag" type="checkbox" value="true">
<input name="RushOrderFlag" type="hidden" value="false">

我的JS功能

function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
    Criteria[this.name] = $("#" + this.name).val();
});
return Criteria;
};

即使在控制台中我把$('[NAME =RushOrderFlag])。VAL(),点击复选框和关闭,它总是返回true之后。

Even if in the console I put $('[name="RushOrderFlag"]').val(), after clicking the check box on and off, it is always returning true.

我在做什么错了?

推荐答案

感谢所有的提示......到底还要更复杂一些,由于剃须刀的复选框创建2输入控件的方式。因此,这里是我必须做的:

Thanks all for the hints...in the end it had to be a bit more complex due to the way the razor creates 2 input controls for the checkbox. So here is what I had to do:

function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
    if ($(this).attr('type') != 'hidden') {
        if ($(this).attr('type') == 'checkbox') {
            Criteria[this.name] = this.checked;
        } else {
            Criteria[this.name] = $("#" + this.name).val();
        }
    }
});
return Criteria;
};

我不喜欢它,因为如果我想有一个隐藏的输入,这将跳过。但现在它的作品。我觉得很难相信,它必须是这个困难:(

I don't like it because if I ever want a hidden input, this will skip that. But for now it works. I find it hard to believe that it has to be this difficult :(

这篇关于MVC 4 EditorFor布尔复选框总是发布真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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