简体   繁体   中英

how to get decimal value from view to controller

I have a input and only for numbers.when i write 5,i can send to controller but 5.5 returns null to controller.I'm using MVC,Bootstrap an Javascript.How can i send to decimal number to controller?

 $(".loader").show(); var thm = {}; thm.thm_cns = $("#thm_cns").val(); thm.thm_tr = $("#thm_tr").val(); thm.thm_year = $("#thm_year").val(); thm.thm_price = $("#thm_price").val(); thm.thm_alan = $("#thm_alan").val(); $.ajax({ type: "POST", url: "/GGE/thm", data: '{thm:' + JSON.stringify(thm) + '}', contentType: "application/json;charset=utf-8", dataType: "json", success: function (json) { alert(json); $("input[type='text']").val(''); $("input[type='number']").val(''); $(".loader").hide(); $("#btn_thm").prop('disabled', false); }, });

in this code i'm trying to get thm_price as a decimal value but i couldn't.

 <div class="col-lg-3 col-sm-pull-3"> <input class="form-control" id="thm_price" name="thm_price" type="number" step="0.1"/> </div>

thm class

 public class thm
{
    public int id { get; set; }
    public string thm_cns{ get; set; }
    public string thm_tr{ get; set; }
    public string thm_year{ get; set; }
    public decimal? thm_price{ get; set; }
    public float thm_alan{ get; set; }
}

and this is controller codes where i'm not getting decimal value.

 [HttpPost]
    public JsonResult thm(thm thm)
    {
        int? d;
        int id = Convert.ToInt32(Session["id"]);
        using (cEntities thm_post= new cEntities())
        {
            d = thm_post.thm_add(id, thm.thm_cns, thm.thm_tr, thm.thm_year, thm.thm_price,tohum.thm_alan);

        }
        if (d > 0)
        {
            return Json("Thm is ok.", JsonRequestBehavior.AllowGet);
        }
        else {
            return Json("Thm is not ok ", JsonRequestBehavior.AllowGet);
        }
    }

Have you tried using .toFixed() ? It forces the value you get from thm_price to a decimal. For instance:

temp = $("#thm_price").val(); thm.thm_price=temp.tofixed(1);

This will give thm_price a decimal with 1 decimal point such as 5.0 instead of just 5.

Or you can try to use parseFloat() such as:

thm.thm_price = parseFloat($("#thm_price").val()).toFixed(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM