为什么发送十进制数时会收到零?

时间:2018-11-01 16:50:09

标签: c# html asp.net-mvc

在我看来,我有两个数字输入(整数或十进制)。如果我发送整数,则应用程序运行良好,但是如果我发送小数,则IDK为什么应用程序接收0

示例:我输入了价格,我写了 12.55 的值,当我请求保存数字时,在我的控制器中该值显示为0 ,因此数据库将其保存为0

我想知道发生了什么

这是我的观点:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" 
      aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Add concept</h4>
        <button type="button" class="close" data-dismiss="modal">×</button>
      </div>
      <div class="modal-body">
      <form>
        <div style="visibility:hidden">
          <input type="text" id="mIdcon" disabled="disabled" />
          <input type="text" id="mIdreq" disabled="disabled" />
        </div>
        <div class="row form-group">
          <div class="col-md-5">
            <label for="mCanti">Quantity</label>
            <input type="text" class="form-control" 
                    id="mCanti" placeholder="Quantity" 
                    onkeypress="return filterFloat(event, this);" />
          </div>
          <div class="col-md-1">
          </div>
          <div class="col-md-6">
            <label for="Fent">Delivery Date:</label>
            <input type="text" class="datefield form-control" 
                    id="Fent" placeholder="DD/MM/AAAA" />
          </div>
        </div>
        <div class="row form-group">
          <div class="col-md-5">
            <label for="UDM">UDM / UOM</label>
            <input type="text" class="form-control" id="mUDM" maxlength="2" 
                    placeholder="UDM / UOM" />
          </div>
          <div class="col-md-1">
          </div>
          <div class="col-md-6">
            <label for="cCta">Acount</label>
            @Html.DropDownList("ctaMAX", null, new { 
              @id = "cCta", 
              @class = "btn btn-primary dropdown-toggle", 
              @style = "color:#777777;background-color:#f8f8f8;border-color:#e7e7e7" })
          </div>
        </div>
        <div class="row form-group">
          <div class="col-md-6">
            <label for="Descripcion">Description</label>
            <input type="text" class="form-control" id="mDes" 
                    placeholder="Description" />
          </div>
          <div class="col-md-6">
            <label for="par">Partialities</label>
            @Html.DropDownList("parci", null, new { 
                @id = "par", 
                @class = "btn btn-primary dropdown-toggle", 
                @style = "color:#777777;background-color:#f8f8f8;border-color:#e7e7e7" })
          </div>
        </div>
        <div class="row form-group">
          <div class="col-md-5">
            <label for="NoParte">Part Number</label>
            <input type="text" class="form-control" id="mNopa" 
                    placeholder="Part Number" />
          </div>
          <div class="col-md-7">
          </div>
        </div>
        <div class="row form-group">
        <div class="col-md-5">
          <label for="Precio">Unit Price</label>
          <input type="text" class="form-control" id="mPrecio" 
                  placeholder="Unit Price" 
                  onkeypress="return filterFloat(event, this);" />
        </div>
        <div class="col-md-7">
        </div>
      </div>
    </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="btnAdd" 
                onclick="return AddConcept();">Add</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">
          Close
        </button>
      </div>
    </div>
  </div>
</div>

这是我的JS:

function AddConcept() {
var res = Validate(); // This function just validate that the inputs aren't empty
if (res == false) {
    return false;
}

var ConceptoObj = {
    idconcepto: $('#mIdcon').val(),
    idreq: $('#idreq').val(),
    cantidad: $('#mCanti').val(),
    UDM: $('#mUDM').val(),
    descripcion: $('#mDes').val(),
    NoParte: $('#mNopa').val(),
    precio: $('#mPrecio').val(),
    FechaEntrega: $('#Fent').val(),
    PagoParcial: $('#par option:selected').val()
};
var c = $('#cCta').val();
var f = $('#fes').val();
var m = $('#mon').val();

$.ajax({
    url: '/Order/AddConcept?cta=' + c + '&fs=' + f + '&cm=' + m,
    data: JSON.stringify(ConceptoObj),
    type: "POST",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (result) {
        CargarConceptosOC();
        AjusteRate();
        if (result == "-100")
            alert("-You have exceeded the limit of concepts for this Requisition-");
        if (result == "-200")
            alert("-There is a problem. Contact the admin-");
        $('#myModal').modal('hide');

    },
    error: function (errormessage) {
        alert(errormessage.responseText);
    }
});

}

这是我的控制者:

public JsonResult AddConcept(ConceptosOC conOC, string cta, string fs, string cm)
{
    int resp = 0, idcon = 0;
    resp = objDB.CUDConceptosOC(conOC, 1);
    DateTime fesol = conOC.FechaEntrega == null 
                        ? DateTime.Today : (DateTime)conOC.FechaEntrega;
    DateTime fcenti;

    decimal rate = Convert.ToDecimal(
                    objDB.SelectCadena("Here I get the dolar price"));
    int renglon = Convert.ToInt32(
                    objDB.SelectCadena("Here I get the row that I want to modify"));

    if (resp == -1)
    {
        idcon = Convert.ToInt32(objDB.SelectCadena("Here I get a specific ID"));

        switch (conOC.PagoParcial)
        {
          case 2:
          // Ignore this
          break;
          default:
            resp = objDB.Ejecutar(
              "INSERT INTO ACOUNTS(ID_CONCEPT, ID_REQUEST, AMOUNT, ACOUNT, REGISTER_DATE, ROW_AFFECTED)" +
              "values(" + idcon + "," + conOC.idreq + "," + 
              ((conOC.cantidad * conOC.precio) * rate).ToString("G", CultureInfo.InvariantCulture) + 
              ",'" + cta + "','" + fesol.ToString("yyyy-MM-dd") + 
              "'," + (renglon + 1) + ")");
            break;
        }
    }
    return Json(resp, JsonRequestBehavior.AllowGet);
}

这是我的对象

public class ConceptosOC
{
    public int idconcepto { get; set; }
    public int idreq { get; set; }
    public decimal cantidad { get; set; }
    public string UDM { get; set; }
    public string descripcion { get; set; }
    public string NoParte { get; set; }
    public decimal precio { get; set; }
    public DateTime? FechaEntrega { get; set; }
    public int PagoParcial { get; set; }

}

这些是我的过滤器功能:

function filterFloat(evt, input) {
var key = window.Event ? evt.which : evt.keyCode;
var chark = String.fromCharCode(key);
var tempValue = input.value + chark;
if (key >= 48 && key <= 57) {
    if (filter(tempValue) === false) {
        return false;
    } else {
        return true;
    }
} else {
    if (key == 8 || key == 13 || key == 0) {
        return true;
    } else if (key == 46) {
        if (filter(tempValue) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}}


function filter(__val__) {
var preg = /^([0-9]+\.?[0-9]{0,4})$/;
if (preg.test(__val__) === true) {
    return true;
} else {
    return false;
}}

1 个答案:

答案 0 :(得分:0)

您可能会收到0,因为它是模型的默认值。这意味着您的应用程序无法将收到的值绑定到模型,因为它无法将其转换回C#模型。这可能与服务器配置区域性的方式有关。您正在发送 12.55 ,如果服务器已配置,则可能会出现类似“ 12,55 ”的消息例如法语或西班牙语。您可以尝试使用实现 System.Web.Mvc.IModelBinder 的自定义模型绑定器来修改十进制值的模型绑定。 您可以尝试这样的事情。定义自定义模型活页夹

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

public class CustomDecimalModelBinder : IModelBinder
{
    /// <summary>
    /// Gets the decimal value from data received
    /// </summary>
    /// <param name="controllerContext">Controller context</param>
    /// <param name="bindingContext">Binding context</param>
    /// <returns>Parsed value</returns>
    public object BindModel(ControllerContext controllerContext, 
                            System.Web.Mvc.ModelBindingContext bindingContext)
    {
        ValueProviderResult result = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);

        var modelState = new System.Web.Mvc.ModelState { 
                                        Value = result 
                                    };

        object actualValue = null;
        var culture = CultureInfo.CurrentCulture;
        if (result.AttemptedValue != string.Empty)
        {
            try
            {
                // Try with your current culture
                actualValue = Convert.ToDecimal(result.AttemptedValue, culture);
            }
            catch (FormatException)
            {
                try
                {
                    // Try with invariant culture if current culture failed
                    actualValue = Convert.ToDecimal(result.AttemptedValue, 
                                                CultureInfo.InvariantCulture);
                }
                catch (FormatException ex)
                {
                    modelState.Errors.Add(ex);
                }
            }
        }
        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}

在您的Application_Start方法中使用它

protected void Application_Start()
{
    // ... normal MVC configuration code

    // This one binds Decimal types
    ModelBinders.Binders.Add(typeof(decimal), new CustomDecimalModelBinder ());
    // This one binds Nullable Decimal types, if you want to support those also
    ModelBinders.Binders.Add(typeof(decimal?), new CustomDecimalModelBinder ());
}