ASP.NET MVC3双重验证(逗号,点,空) [英] ASP.NET MVC3 double validation (comma, point, null)

查看:125
本文介绍了ASP.NET MVC3双重验证(逗号,点,空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器看起来是这样的:

My controller looks like this:

 public class PortefeuilleController : Controller
    {
            public ActionResult Create()
            {
                return View(new PortefeuilleViewModel{Saldo = 0.0});
            }
    }

我创建视图看起来是这样的:

My create view looks like this:

@model PortefeuilleViewModel

@{
    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>PortefeuilleViewModel</legend>

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

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

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

和我PortefeuilleViewModel是这样的:

And my PortefeuilleViewModel looks like this:

public class PortefeuilleViewModel
{
    [DisplayName("Naam")]
    [Required(ErrorMessage = "Gelieve een naam in te voeren")]
    public string Naam { get; set; }

    [DisplayName("Saldo")]
    public double Saldo { get; set; }
}

我的问题出在Saldo字段。我想验证它,如下所示:

My problem lies with the "Saldo" field. I want to validate it as follows:

让该字段为空应该是有效的(因为我的code,后面会发生变化转变为0.0,并保存在数据库中值)。但是,例如,既'19,99'和'19 .99'也应为有效传递。其余全是无效的。

Leaving the field empty should be valid (because my code-behind will change "" into "0.0" and save that value in the database). But, for example, both '19,99' and '19.99' should also be passed as being valid. All the rest is invalid.

我真的不知道我怎么能拉这一关。我已经发现这篇文章: http://haacked.com /archive/2011/03/19/fixing-binding-to-decimals.aspx
但是,这并没有解决(第二部分),我的问题在所有...

I don't really know how I can pull this off. I already found this article: http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx But that didn't solve (the second part of) my problem at all...

任何帮助将大大AP preciated。谢谢你。

Any help would be greatly appreciated. Thanks.

推荐答案

确定,所以你必须在验证2级激活:服务器端和客户端。让我们先来处理服务器端验证的问题。

OK, so you have validation activated at 2 levels: server side and client side. Let's first deal with the server side validation issue.

用钱时的第一件事情(这是我假设 Saldo 现场重新presents是使用小数,而不是双打)。所以,第一个变化是:

The first thing when working with money (which is what I suppose the Saldo field represents is to use decimals, not doubles). So the first change would be:

[DisplayName("Saldo")]
public decimal Saldo { get; set; }

好了,现在让我们适应了一点Haacked模型绑定到你的情况(接受为十进制分离器以及空值)

OK, now let's adapt a little the Haacked model binder to your situation (accepting . and , as decimal separator as well as empty values)

public class DecimalModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (string.IsNullOrEmpty(valueResult.AttemptedValue))
        {
            return 0m;
        }
        var modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDecimal(
                valueResult.AttemptedValue.Replace(",", "."), 
                CultureInfo.InvariantCulture
            );
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

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

这当然会在的Application_Start 注册:

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

目前这个阶段,我们已经解决了服务器端验证问题。至于客户端验证而言,你可以使用jQuery全球化插件中,微软发布。斯科特Hanselman有同样的blogged关于它。所以,一旦你安装它,你可能会迫使客户端的文化和覆盖负责执行客户端验证的 $ validator.methods.number 方法:

At this stage we have solved the server side validation issue. As far as the client side validation is concerned you could use the jQuery globalization plugin that Microsoft released. Scott Hanselman has also blogged about it. So once you install it you could force the client side culture and override the $.validator.methods.number method which is responsible for performing the client side validation:

$.validator.methods.number = function (value, element) {
    // TODO: return true or false if value is a valid decimal
}

这篇关于ASP.NET MVC3双重验证(逗号,点,空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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