MVC 3 客户端验证,模型绑定十进制值和文化(不同的十进制分隔符) [英] MVC 3 client side validation, model binding decimal value and culture (different decimal separator)

查看:18
本文介绍了MVC 3 客户端验证,模型绑定十进制值和文化(不同的十进制分隔符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的客户端验证(模型绑定)支持不同的文化,并且我发现了一个关于我正在尝试实施的主题的有趣博客.

http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx

波哥

 公共类 Jogador{公共 int ID { 获取;放;}公共字符串名称 { 获取;放;}公共十进制薪水{得到;放;}}

我有我的自定义 DecimalModelBinder 类

 公共类 DecimalModelBinder : IModelBinder{公共对象 BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);ModelState modelState = new ModelState {Value = valueResult};对象实际值 = 空;尝试{实际值 = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);}捕获(格式异常 e){modelState.Errors.Add(e);}bindingContext.ModelState.Add(bindingContext.ModelName, modelState);返回实际值;}}

我的 web.config:

<组件><add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></组件></编译><认证模式=表单"><forms loginUrl="~/Account/LogOn" timeout="2880"/></认证><页面><命名空间><add namespace="System.Web.Helpers"/><add namespace="System.Web.Mvc"/><add namespace="System.Web.Mvc.Ajax"/><add namespace="System.Web.Mvc.Html"/><add namespace="System.Web.Routing"/><add namespace="System.Web.WebPages"/></命名空间></页面>

Global.asax 被更改为在十进制和十进制上使用我的自定义 ModelBinder?值

protected void Application_Start(){AreaRegistration.RegisterAllAreas();ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());RegisterGlobalFilters(GlobalFilters.Filters);RegisterRoutes(RouteTable.Routes);}

在我的视图中输入的十进制数以,"作为小数点分隔符时,客户端验证仍然失败.它不能同时处理,"和.".js 验证似乎没有考虑我的自定义绑定

一遍又一遍地阅读博客文章,我似乎无法弄清楚我错过了什么.

这是视图:

@model MVC_Empty.Web.Models.Jogador@{ViewBag.Title = "创建";}<h2>创建</h2><script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>@using (Html.BeginForm()) {@Html.ValidationSummary(true)<字段集><legend>Jogador</legend><div class="editor-label">@Html.LabelFor(model => model.Name)

<div class="editor-field">@Html.EditorFor(model => model.Name)@Html.ValidationMessageFor(model =>model.Name)

<div class="editor-label">@Html.LabelFor(model => model.Salary)

<div class="editor-field">@Html.EditorFor(model => model.Salary)@Html.ValidationMessageFor(model => model.Salary)

<p><输入类型=提交"值=创建"/></p></fieldset>}<div>@Html.ActionLink("返回列表", "索引")

服务器端验证看起来不错,但是如何处理客户端验证以便在单击提交按钮时发送 POST.

javascript 验证不处理逗号.

解决方案

最后,通过了解自定义 DecimalModelBinder 只会处理服务器端验证,而不影响处理客户端验证的 jquery.validate.js,我找到了解决问题的方法.

扩展验证解决了我的问题.

通过新的 .js 文件扩展验证作为问题的解决方法:

$.validator.methods.number = function(value, element) {返回 this.optional(element) ||/^-?(?:d+|d{1,3}(?:[s.,]d{3})+)(?:[.,]d+)?$/.测试(值);};

这个博客真的很有帮助http://rebuildall.umbraworks.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator

I am trying to have my client side validation (model binding) to support different cultures, and I found an interesting blog on the subject on which I am trying to implement.

http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx

Poco

  public class Jogador
  {
    public int ID { get; set; }

    public string Name { get; set; }

    public decimal Salary { get; set; }
  }

I've got my custom DecimalModelBinder class

  public class DecimalModelBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
      ModelState modelState = new ModelState {Value = valueResult};

      object actualValue = null;
      try
      {
        actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
      }
      catch (FormatException e)
      {
        modelState.Errors.Add(e);
      }

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
      return actualValue;
    }
  }

My web.config:

<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  </assemblies>
</compilation>

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages"/>
  </namespaces>
</pages>

Global.asax are altered to use my custom ModelBinder on decimal and decimal? values

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();

  ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
  ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);
}

Still the client-side validation fails on decimal entered in my view with a "," as a decimal separator. It does not handle both "," and ".". The js validation does not seem to take my custom binding in consideration

Reading the blog article over and over again, I just can't seem to figure out what I am missing.

Here is the view:

@model MVC_Empty.Web.Models.Jogador

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Jogador</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Salary)
            @Html.ValidationMessageFor(model => model.Salary)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Server side validation seems fine, but how to handle the client-side validation in order to send a POST when clicking the submit button.

The javascript validation does not handle the comma.

解决方案

Finally, by understanding that the Custom DecimalModelBinder would only handle server-side validation and not affect the jquery.validate.js which handles the client-side validation, I found a solution to the problem.

Extending the validation solved my issue.

Extend the validation by a new .js file as a workaround to the problem:

$.validator.methods.number = function(value, element) {
  return this.optional(element) || /^-?(?:d+|d{1,3}(?:[s.,]d{3})+)(?:[.,]d+)?$/ .test(value);
};

This blog was really helpful http://rebuildall.umbraworks.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator

这篇关于MVC 3 客户端验证,模型绑定十进制值和文化(不同的十进制分隔符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆