mvc3 中的十进制错误 - 该值对字段无效 [英] error with decimal in mvc3 - the value is not valid for field

查看:13
本文介绍了mvc3 中的十进制错误 - 该值对字段无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何解决这个问题?

型号:

 公共类电影{公共 int ID { 获取;放;}公共字符串标题{获取;放;}公共日期时间发布日期{获取;放;}公共字符串流派{获取;放;}公共十进制价格{得到;放;}}公共类 MovieDbContext : DbContext{公共数据库集<电影>电影 { 得到;放;}}

控制器:

public class MovieController : Controller{private MovieDbContext db = new MovieDbContext();////获取:/电影/公共视图结果索引(){var 电影 = 来自 db.Movies 中的 m其中 m.ReleaseDate >新日期时间(1984, 6, 1)选择 m;返回视图(电影.ToList());}////获取:/电影/详细信息/5公共视图结果详细信息(int id){电影电影 = db.Movies.Find(id);返回视图(电影);}////获取:/电影/创建公共 ActionResult 创建(){返回视图();}////发布:/电影/创建[HttpPost]公共 ActionResult 创建(电影电影){如果(模型状态.IsValid){db.Movies.Add(电影);db.SaveChanges();return RedirectToAction("索引");}返回视图(电影);}////获取:/电影/编辑/5公共操作结果编辑(int id){电影电影 = db.Movies.Find(id);返回视图(电影);}////发布:/电影/编辑/5[HttpPost]公共动作结果编辑(电影电影){如果(模型状态.IsValid){db.Entry(movie).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("索引");}返回视图(电影);}////获取:/电影/删除/5公共操作结果删除(int id){电影电影 = db.Movies.Find(id);返回视图(电影);}////发布:/电影/删除/5[HttpPost, ActionName("删除")]公共 ActionResult DeleteConfirmed(int id){电影电影 = db.Movies.Find(id);db.Movies.Remove(电影);db.SaveChanges();return RedirectToAction("索引");}受保护的覆盖无效处置(布尔处置){db.Dispose();base.Dispose(处置);}}}

查看:

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

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

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

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

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

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

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

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

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

公共数据库集<电影>电影 { 得到;放;}}

解决方案

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

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

使用系统;使用 System.Globalization;使用 System.Web.Mvc;命名空间 你的命名空间{公共类 DecimalModelBinder : IModelBinder{公共对象 BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);ModelState modelState = new ModelState { Value = valueResult };对象实际值 = 空;if(valueResult.AttemptedValue != string.Empty){尝试{实际值 = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);}捕获(格式异常 e){modelState.Errors.Add(e);}}bindingContext.ModelState.Add(bindingContext.ModelName, modelState);返回实际值;}}}

Global.asax.cs, 中像这样在 Application_Start() 中使用它:

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

I'm following [Getting started with ASP.NET MVC 3][1]. And I can't add/edit with value of Price = 9.99 or 9,99. It said: "The value '9.99' is not valid for Price." and "The field Price must be a number."

How to fix this?

Model:

    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; }
}

Controller:

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);
    }
}
}

View:

    @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; }
}

解决方案

I just stumbled on this again after 2 years. I thought ASP.NET MVC 5 had solved this but looks like it's not the case. So here goes how to solve the problem...

Create a class called DecimalModelBinder like the following and add it to the root of your project for example:

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;
        }
    }
}

Inside Global.asax.cs, make use of it in Application_Start() like this:

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

这篇关于mvc3 中的十进制错误 - 该值对字段无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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