【问题标题】:MVC 4 Validate a checkbox without using JQueryMVC 4 在不使用 JQuery 的情况下验证复选框
【发布时间】:2012-12-07 18:40:45
【问题描述】:

我目前正在尝试验证付款表单上的条款和条件复选框,以便在选中条款和条件复选框之前不会提交表单。

我正在创建的特定表单仅供一组使用 IE6 的客户使用(因此我无法使用 JQuery 进行验证)。

我已经用所需的数据注释修饰了条款和条件 bool 模型值,但未显示所需的错误消息(与使用字符串、十进制或 int 等的其他值不同。

我已经设法使用此代码显示错误:

if (ModelState.IsValid && model.TermsAndConditions)
            {
                ConnectAndRedirectoToProtx(model);
            }
            else
            {
                //store locally and sort later
                TempData["message"] = "You must first read through and agree to the terms and conditions";
            }

此代码在控制器的 HttpPost Index ActionResult 中找到,然后我在视图中呈现如下:

div style="color: red;font-weight:bold;">@TempData["message"]</div>

使用这个 cpde 的问题是它只显示所有其他字段是否正确,是否可以不使用 JQuery 显示此错误消息以及单击提交按钮后立即显示的其他错误消息?

【问题讨论】:

  • 还有人用IE6???

标签: jquery checkbox asp.net-mvc-4 model-validation


【解决方案1】:

必需的数据注释标记在您的情况下不起作用,因为即使未选中的复选框也会将错误值传递给模型。 如果不支持 JQuery,您可以使用 Java Script(直到这也被浏览器阻止。) 请访问以下链接寻求帮助。

http://www.w3schools.com/js/js_form_validation.asp

您还可以更改控制器功能,如下所示,仅针对这种情况跟踪错误

if(!model.TermsAndConditions)
{
    TempData["message"] = "You must first read through and agree to the terms and conditions";
}

if (ModelState.IsValid)
        {
            ConnectAndRedirectoToProtx(model);
        }
        else
        {
            //store locally and sort later
            TempData["message"] = "Invalid Model or some other error message......";
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-28
    • 2011-02-12
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多