Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - C# MVC Controller cannot get decimal or double values from Ajax POST request

My problem is that when I try to send a double or decimal via ajax into my C# MVC Controller the value is always null. I can send the value as string and I can send Integers without a problem. Why can't I send values with decimals? When I check the request that is sent from the client the correct value is there (Form Data is price=84.50).

Error:

The parameters dictionary contains a null entry for parameter 'price' of non-nullable type 'System.Decimal'

Html:

 <input type="number" step="1" class="form-control" name="price" id="price">
 <button type="button" class="btn btn-success">Send</button>

Javascript:

$('.btn-success').click(function () {

    //var price = $('#price').val(); - Did not work
    //var price = Number($('#price').val()); Did not work
    var price = Number($('#price').val()).toFixed(2); // Does not work

    $.ajax({
        url: 'PriceFunction',
        type: 'POST',
        data: {
            price: price,
        }
    }).done(function () {

    }).fail(function () {
        console.log("Error in ajaxfunction!");
    });
});

C#:

    [HttpPost]
    public void PriceFunction(decimal price)
    {
     // I have tried with decimal, double and double?.     
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to stringify you data when you are sending decimal values.

data: JSON.stringify({ Price: 5.0 })

This is because the decimal is considered an integer by the default binder.

You could of course change to using the DecimalModelBinder which is detailed at the following link:

ASP.NET MVC3 JSON decimal binding woes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...