【问题标题】:MVC Foolproof validation - Cannot read property 'value' of undefinedMVC 万无一失的验证 - 无法读取未定义的属性“值”
【发布时间】:2015-11-25 07:34:08
【问题描述】:

我在我的应用程序中使用MVC Foolproof validation。 场景是我有一个名为 CustomerType 的下拉列表,其中包含以下值

 Id     Name
 1      Student
 2      Non-Employed
 3      Employed
 4      SelfEmployed

我的视图模型中还有一个属性public string CompanyAddress{ get; set; }。我的目标是使 CompanyAddress required if 下拉列表具有值 3 or 4

我已经尝试了以下

   [Required(ErrorMessage = "Please select status of the customer", AllowEmptyStrings = false)]
    public int? customerTypeID { get; set; }
    public SelectList customerTypeList { get; set; }

   [RequiredIf("IsCompanyAddressRequired", true, ErrorMessage = "please enter company address")]
    public string CompanyAddress { get; set; }


 public bool IsCompanyAddressRequired
    {
        get
        {
            if (customerTypeID == 3 || customerTypeID == 4)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

    }

上面的代码在服务器端正常工作,但在客户端我收到以下错误

 `Uncaught TypeError: Cannot read property 'value' of undefined`

验证被引用如下

 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/plugins/jQueryVal/jquery.unobtrusive*",
                    "~/plugins/jQueryVal/jquery.validate*",
                    "~/plugins/foolproofValidation/MvcFoolproofJQueryValidation.min.js",
                    "~/plugins/foolproofValidation/mvcfoolproof.unobtrusive.min.js",
                    "~/plugins/foolproofValidation/MvcFoolproofValidation.min.js"
                    ));

【问题讨论】:

  • 除非您在视图中为属性IsCompanyAddressRequired 生成输入(然后您需要根据下拉列表中的选定值动态更新它。Insread,使用[GreaterThan("customerTypeID", 2)]并删除bool 属性
  • 感谢您的回复..这里我收到错误Foolproof.GreaterThanAttribute does not contain a constructor that take 2 arguments.
  • 对不起,对我自己的验证属性感到困惑 :) - 让我检查一下文档(甚至不确定万无一失是否支持这一点)
  • 看起来应该是[RequiredIf("customerTypeID", Operator.GreaterThan, 2, ErrorMessage = "..")]
  • 感谢它的工作,请发布答案..:)

标签: asp.net-mvc-4 unobtrusive-validation foolproof-validation


【解决方案1】:

除非您要生成输入(例如)<input name="IsCompanyAddressRequired" value="false" />(或 value="true",具体取决于 customerTypeID 的初始值),否则您的验证属性无法在客户端上运行,然后动态更新 value 属性更改下拉列表值时使用 javascript。

改为使用

[RequiredIf("customerTypeID", Operator.GreaterThan, 2, ErrorMessage = "..")]
public string CompanyAddress { get; set; }

并删除您的 IsCompanyAddressRequired 属性。

【讨论】:

    猜你喜欢
    • 2014-06-25
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多