Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery + Asp.Net MVC, passing float number

I'm working with MVC recently and I've encountered a strange problem while trying to send request to my controller using ajax. I'm using JQuery (version 1.3.2) that came directly with MVC, I'm trying to send such ajax request:

$.post("Home/OpenTrade", { price: 1.5 }, function() { }, "json");

I've also tried parseFloat("1.5") instead of 1.5.
When I try to receive this value in controller using

[AcceptVerbs( HttpVerbs.Post)]
public void OpenTrade(float? price)

My price is always null. If I omit ? the controller is not called at all (which is nothing surprising), I've tried using decimal as well as double type. Furthermore, this function works when I'm sending integer data (if I send 1 this controller is called, and float? price is filled properly). Am I missing something, or is it a bug?

Ad. I can receive price as string, and then parse it manually, but I don't like this solution, as it's not elegant and it fights the whole purpose of using framework like MVC to do this for me.

Edit & Answer: Using Joel's advice, I've created a Model Binder, which I'll post, maybe someone will use it:


class DoubleModelBinder : IModelBinder
{
    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext    bindingContext)
    {
        string numStr = bindingContext.ValueProvider[bindingContext.ModelName].AttemptedValue;
        double res;

        if (!double.TryParse(numStr, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out res))
        {
            if (bindingContext.ModelType == typeof(double?))
                return null;
            throw new ArgumentException();
        }

        if (bindingContext.ModelType == typeof(double?))
            return new Nullable<double>(res);
        else
            return res;
    }

    #endregion
}

It may be registered as double and double? binder, for double? it will pass null to controller, if value could not have been resolved.

Btw. Any ideas why floats and doubles don't work out of the box (for me?)?

Edit2 & Solution: Ok, this is going to be funny :). It didn't work for me, because requested string was sending 1.5432 (an example value), which is perfectly ok, but... MVC was trying to decode it internally using my culture settings, which are expecting numbers to be in format 1,5432, so the conversion has failed silently.
So, thing to remember: if you are living in strange country, double-check your culture settings.

like image 290
Marcin Deptuła Avatar asked Aug 17 '09 01:08

Marcin Deptuła


2 Answers

make a float model binder. That can pull the appropriate value from the form collection, parse it, and return it as the argument

like image 53
Joel Martinez Avatar answered Oct 23 '22 22:10

Joel Martinez


{ price: '1,5' } 

should be fine.

like image 41
toma19 Avatar answered Oct 23 '22 20:10

toma19