31

我正在关注 [ASP.NET MVC 3 入门][1]。而且我无法使用 Price = 9.99 或 9,99 的值添加/编辑。它说:“价值'9.99'对价格无效。” 和“价格字段必须是数字。”

如何解决这个问题?

模型:

    public class Movie
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

public class MovieDbContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

控制器:

public class MovieController : Controller
{
    private MovieDbContext db = new MovieDbContext();

    //
    // GET: /Movie/

    public ViewResult Index()
    {
        var movie = from m in db.Movies
                     where m.ReleaseDate > new DateTime(1984, 6, 1)
                     select m;

        return View(movie.ToList()); 
    }

    //
    // GET: /Movie/Details/5

    public ViewResult Details(int id)
    {
        Movie movie = db.Movies.Find(id);
        return View(movie);
    }

    //
    // GET: /Movie/Create

    public ActionResult Create()
    {
        return View();
    } 

    //
    // POST: /Movie/Create

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            db.Movies.Add(movie);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        return View(movie);
    }

    //
    // GET: /Movie/Edit/5

    public ActionResult Edit(int id)
    {
        Movie movie = db.Movies.Find(id);
        return View(movie);
    }

    //
    // POST: /Movie/Edit/5

    [HttpPost]
    public ActionResult Edit(Movie movie)
    {
        if (ModelState.IsValid)
        {
            db.Entry(movie).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(movie);
    }

    //
    // GET: /Movie/Delete/5

    public ActionResult Delete(int id)
    {
        Movie movie = db.Movies.Find(id);
        return View(movie);
    }

    //
    // POST: /Movie/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {            
        Movie movie = db.Movies.Find(id);
        db.Movies.Remove(movie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}
}

看法:

    @model MvcMovies.Models.Movie

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

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

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

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

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

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

<div>
@Html.ActionLink("Back to List", "Index")
</div>
public DbSet<Movie> Movies { get; set; }
}
4

10 回答 10

41

2年后,我再次偶然发现了这一点。我以为 ASP.NET MVC 5 已经解决了这个问题,但看起来情况并非如此。所以这里是如何解决这个问题......

创建一个DecimalModelBinder如下所示的类并将其添加到项目的根目录中,例如:

using System;
using System.Globalization;
using System.Web.Mvc;

namespace YourNamespace
{   
    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;

            if(valueResult.AttemptedValue != string.Empty)
            {
                try
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
                }
                catch(FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

            return actualValue;
        }
    }
}

在里面这样Global.asax.cs,使用它Application_Start()

ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
于 2013-10-12T21:35:03.743 回答
7

您是 MS 没有预见到的非英语客户之一。您将需要付出一些额外的努力来运行您的版本。我遇到了类似的问题,拒绝将“9,99”和“9.99”作为有效数字。似乎一旦服务器端验证失败,一旦客户端验证失败,导致没有数字被接受。

所以你必须使验证一致。

就像评论中建议的那样,看看 http://msdn.microsoft.com/en-us/library/gg674880(VS.98).aspxhttp://haacked.com/archive/2010/05/10 /globalizing-mvc-validation.aspxMVC 3 jQuery Validation/globalizing of number/decimal field 或者 - 你应该理解德语(或者只看代码示例) http://www.andreas-reiff.de/2012/06 /probleme-mit-mvcmovies-beispiel-validierung-des-preises-mit-dezimalstellen-schlagt-fehl/

顺便说一句,音乐和电影示例教程都存在同样的问题。

于 2012-08-06T09:13:24.010 回答
4

我在荷兰的 PC 上为英语受众开发 Web 应用程序时遇到了这个问题。

double 类型的模型属性生成此服务器端验证错误:

值“1.5”对 无效。

在断点处,我在即时窗口中看到了这些值:

?System.Threading.Thread.CurrentThread.CurrentUICulture

{zh-CN}

?System.Threading.Thread.CurrentThread.CurrentCulture

{nl-NL}

作为一种解决方案(或者可能是一种变通方法),您可以在 web.config 文件中指定全球化设置。

<configuration>
  <system.web>
    <globalization culture="en" uiCulture="en" />

当然,这意味着您强制用户输入英文格式的数字,但在我的情况下,这很好。

于 2017-02-03T13:12:18.437 回答
4

2019年,这个问题还没有解决。使用 ASP Core 2.1,我的 UI 是法语的(小数分隔符 = ','),而且只要我有十进制数,我就无法进行验证。

我找到了一种解决方法,但并不理想:我创建了一个基于法语的 CultureInfo,但我将小数分隔符更改为与 Invariant Culture 中的相同:'.'。

这成功了,我的十进制数字现在显示为美国风格(但我可以接受)并且验证有效。

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });


        //Culture specific problems
        var cultureInfo = new CultureInfo("fr-FR");
        cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
        System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;

    }
于 2019-07-11T21:33:36.370 回答
1

我对 Leniel Macaferi 的代码做了一些修改,因此您可以将其用于任何类型:

public class RequestModelBinder<TBinding> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);

        ModelState modelState = new ModelState { Value = valueResult };

        object actualValue = null;

        if (valueResult.AttemptedValue != string.Empty)
        {
            try
            {
                // values really should be invariant
                actualValue = Convert.ChangeType(valueResult.AttemptedValue, typeof(TBinding), CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

        return actualValue;
    }
}
于 2016-08-19T12:27:42.907 回答
1

我试过@Leniel Macaferi,但它对我不起作用。

ModelState.IsValid 不接受格式为 7.000,00 的数字

当我从以下位置更改属性类型时,问题就开始了:

[Column("PRICE")]
public decimal Price { get; set; }

[Column("PRICE")]
public decimal? Price { get; set; }

我还尝试在 web.config 中包含我忘记的全球化

<globalization culture="pt-BR" uiCulture="pt-BR" enableClientBasedCulture="true" />

唯一有效的解决方法是将属性更改回仅十进制:

[Column("PRICE")]
public decimal Price { get; set; }

并且还将表列更改为不接受空值

希望它可以帮助某人。

于 2017-03-03T18:01:38.600 回答
0

我通过禁用 jquery 的价格解决了这个问题,并且只在服务器端验证该输入。我在这里找到了答案: ASP .NET MVC Disable Client Side Validation at Per-Field Level

<div class="col-md-10">
                @{ Html.EnableClientValidation(false); }
                @Html.EditorFor(model => model.DecimalValue, new { htmlAttributes = new { @class = "form-control" } })
                @{ Html.EnableClientValidation(true); }
                @Html.ValidationMessageFor(model => model.DecimalValue, "", new { @class = "text-danger" })
            </div>
于 2016-05-10T10:03:19.233 回答
0

你可以加:

protected void Application_BeginRequest()
{
    var currentCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
    currentCulture.NumberFormat.NumberDecimalSeparator = ".";
    currentCulture.NumberFormat.NumberGroupSeparator = " ";
    currentCulture.NumberFormat.CurrencyDecimalSeparator = ".";

    Thread.CurrentThread.CurrentCulture = currentCulture;
    //Thread.CurrentThread.CurrentUICulture = currentCulture;
}

Global.asax(在 MVC 5.1 上测试)。它可以在不改变 UICulture 的情况下为我工作。

于 2015-12-23T20:23:51.550 回答
0

这是Leniel Maccaferri解决方案的扩展,它避免了与用户代理以与服务器不同的文化格式发送十进制值相关的问题。它的限制绑定到千位分隔符解析,当它是值中唯一的分隔符时,可能会引发错误的绑定。

/// <summary>
/// custom decimal model binder
/// </summary>
/// <author>https://stackoverflow.com/users/114029/leniel-maccaferri</author>
/// <see cref="https://stackoverflow.com/a/19339424/3762855"/>
/// <remarks>Integrated with a fix for the decimal separator issue.
/// <para>This issue maybe depends from browsers interpretation of decimal values posted-back to the server when they receive response without any http content-language specific indication.</para>
/// <para>Important! decimal values caming from UI must not be formatted with thousands separator.</para>
/// </remarks>
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;

        if (valueResult.AttemptedValue != string.Empty)
        {
            try
            {
                var culture = Thread.CurrentThread.CurrentCulture;

                //This is needed to convert in the right manner decimal values coming from UI, as seems they always represent the decimal separator as a period("."). 
                //Maybe depends from browsers interpretation of decimal values posted-back to the server when they receive response without any http content-language specific indication.
                if (culture.NumberFormat.NumberDecimalSeparator == "," && valueResult.AttemptedValue.LastIndexOf(".") > 0)
                {
                    culture = new CultureInfo("en"); 
                }
                else if (Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator == "." && valueResult.AttemptedValue.LastIndexOf(",") > 0)
                {
                    culture = new CultureInfo("it");
                }

                actualValue = Convert.ToDecimal(valueResult.AttemptedValue, culture);

            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

        return actualValue;
    }
}
于 2021-01-20T10:27:36.470 回答
-4

只需评论此脚本的链接:

<%--<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>--%>
于 2014-02-21T07:54:20.640 回答