【问题标题】:Send decimal number with commas working on c sharp mvc用逗号发送十进制数,在 c sharp mvc 上工作
【发布时间】:2017-10-07 21:47:47
【问题描述】:

这是我第一次参加这个非常有趣的论坛。 我正在做一个 mvc 项目。我有我的模型,里面有一个货币的小数属性。我也有它的编辑视图,我在其中使用 Html Helper TextEditorFor。此 Html Helper 在网页上显示来自 de Database 的一个值,但它显示为带逗号的小数。然后,当我想再次发送此编辑而不进行任何编辑时,它不会向数据库发送任何内容并显示错误的 TextEditBox,我需要在其中更改逗号以便能够将此数据发送到数据库。我希望我能正确解释它:P

这是我的模型:

[Display(Name = "Hardware purchasing")]
[DataType(DataType.Currency)]
public decimal Hardware { get; set; }

这就是风景

<div class="form-group ">
@Html.LabelFor(model => model.Hardware,  htmlAttributes: new { @class = "control-label col-md-2 col-xs-6" })
<div class="col-md-1 col-xs-3 ">
    @Html.EditorFor(model => model.Hardware, new { htmlAttributes = new { @class = "form-control text-center" } })
    @*@Html.ValidationMessageFor(model => model.Hardware, "", new { @class = "text-danger" })*@
</div>

我一直在寻找一些方法,让我将这个带有逗号的数字转换为十进制,以便发送到数据库。也许在控制器中获取 html 值并对其进行转换,但我不知道这是否是正确的方法。 我希望你能帮助我。非常感谢。

【问题讨论】:

  • 如果你使用十进制数据类型,你应该从十进制值中去掉逗号。
  • 向我们展示一些演示数据以了解正在发生的事情....数据库中有什么以及您在 HTML 中得到了什么...只有描述将无济于事..
  • 提供控制器动作方法代码,你是使用默认模型绑定器还是使用请求参数?
  • 感谢您的回答。我仍然对代码以及在哪里引入它有一些疑问。我添加了一个新答案,其中包含有关我的项目的更多信息。

标签: c# asp.net-mvc decimal


【解决方案1】:

如果您在数据库的文本框中遇到这样的情况

然后我们需要为自定义模型绑定器创建模型

型号

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

之后,您必须在应用程序启动时将其注册到 globle.asax 文件中。

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

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

通过这种方式,您将获得 Hardware 字段现在将接受 2200800.50 和 2,200,800.50。

【讨论】:

    【解决方案2】:

    这不是答案。我要补全资料... 首先,感谢您的回答。 我的控制器的名称是 ConsultasController,它是在使用视图和实体框架选项创建后由默认的 .net mvc 代码制成的。这是我想与编辑功能一起使用的代码:

    public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Consulta consulta = db.Consultas.Find(id);
            if (consulta == null)
            {
                return HttpNotFound();
            }
            return View(consulta);
        }
    
    
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ConsultaID,Usuario,FechaEntrada,Hardware,HardwareY,Software,SoftwareY,MaterialConsultaAlta,MaterialConsultaAltaY,InstalTelefonoInternet,InstalTelefonoInternetY,AlquilerOficina,AlquilerOficinaY,MobiliarioOficina,MobiliarioOficinaY,ImagenProfesional,ImagenProfesionalY,GastosEstablVarios,GastosEstablVariosY,MaterialConsultaRenov,MaterialConsultaRenovY,HardwareRenov,HardwareRenovY,SoftwareRenov,SoftwareRenovY,Afiliaciones,AfiliacionesY,Proteccion,ProteccionY,DominioInternet,DominioInternetY,MaterialFungible,MaterialFungibleY,Formacion,FormacionY, Publicidad, PublicidadY,Imprevistos,ImprevistosY,PRL,PRLY,GastosAnualesVarios,GastosAnualesVariosY,AlquilerOficinaMensual,AlquilerOficinaMensualY,SeguridadSocial,SeguridadSocialY,SeguroMedico,SeguroMedicoY,LuzCalefaccion,LuzCalefaccionY,GestoriaLitigios,GestoriaLitigiosY,AsesoriaAveriasInf,AsesoriaAveriasInfY,AlojamientoWeb,AlojamientoWebY,TelefonoInternetMensual,TelefonoInternetMensualY,GastosMensualesVarios,GastosMensualesVariosY,DiasVacaciones,DiasFestivos,DiasImprevistos,DiasTrabajoSemana,DiasFormacion,DiasGestiones,HorasTraduccion,TrabajoProductivo,Rendimiento,PrecioPalabra,PagasAnual,IRPF,SueldoMensual,NumeroPagas,IRPFdc,SueldoMensualdt,NumeroPagasdt,TarifaCobro,RendimientoDT")] Consulta consulta)
    
        {
            if (ModelState.IsValid)
            {
                db.Entry(consulta).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(consulta);
        }
    

    我没有修改任何重要的东西。 视图中的结果应显示为 123,23€,用逗号分隔小数点,我需要将其翻译为 133.23€,并带有 sql BD 接受的点。 我已经观察了你的答案,但我不明白我必须把这些代码放在哪里。我是否要制作一个新模型或将它们插入到控制器中? 谢谢!

    【讨论】:

    • 不,你不需要编写新模型,你只需要编写一个继承自 DefaultModelBInder 的 ModelBInder 类并覆盖 BindModel() 方法,我已经更新了上面的答案。
    【解决方案3】:

    默认 MVC 模型绑定器无法解析格式化显示的值。所以,很可能你最终会为你的 Model 类编写自己的 Binder 并在 Application_Start 中注册:

    public class Test
        {
            [Display(Name = "Hardware purchasing")]
            [DataType(DataType.Currency)]
            public decimal Hardware { get; set; }
        }
    

    如下创建自定义模型绑定器:

        public class TestModelBinder : DefaultModelBinder
         {
            public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
                {
                    var result = bindingContext.ValueProvider.GetValue("Hardware");
    
                    if (result != null)
                    {
                        decimal hardware;
                        if (Decimal.TryParse(result.AttemptedValue, NumberStyles.Currency, null, out hardware))
                        return new Test { Hardware = hardware };
    
                    bindingContext.ModelState.AddModelError("Hardware", "Wrong amount format");
                }
    
                return base.BindModel(controllerContext, bindingContext);
            }
        }
    

    将其注册到 Global.asax 中的 Application_Start()

    ModelBinders.Binders.Add(typeof(Test), new TestModelBinder());
    

    只需如上所述编写 ModelBinder,然后在您的控制器操作方法中。让框架知道要使用的模型绑定器,即不是默认的,而是您自定义的

    public ActionResult Edit([ModelBinder(typeof(TestModelBinder ))] TestModelBinder test)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      相关资源
      最近更新 更多