Note that there are some explanatory texts on larger screens.

plurals
  1. POJQuery + Asp.Net MVC, passing float number
    text
    copied!<p>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:</p> <pre><code>$.post("Home/OpenTrade", { price: 1.5 }, function() { }, "json"); </code></pre> <p>I've also tried <code>parseFloat("1.5")</code> instead of <code>1.5</code>.<br> When I try to receive this value in controller using</p> <pre><code>[AcceptVerbs( HttpVerbs.Post)] public void OpenTrade(float? price) </code></pre> <p>My price is always null. If I omit <code>?</code> the controller is not called at all (which is nothing surprising), I've tried using <code>decimal</code> as well as <code>double</code> type. Furthermore, this function works when I'm sending integer data (if I send <code>1</code> this controller is called, and <code>float? price</code> is filled properly). Am I missing something, or is it a bug?</p> <p>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.</p> <p>Edit &amp; Answer: Using Joel's advice, I've created a Model Binder, which I'll post, maybe someone will use it:</p> <pre><code> 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&lt;double>(res); else return res; } #endregion } </code></pre> <p>It may be registered as double and double? binder, for double? it will pass null to controller, if value could not have been resolved. </p> <p>Btw. Any ideas why floats and doubles don't work out of the box (for me?)?</p> <p><b>Edit2 &amp; Solution:</b> Ok, this is going to be funny :). It didn't work for me, because requested string was sending <code>1.5432</code> (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<b>,</b>5432, so the conversion has failed silently.<br> So, thing to remember: if you are living in strange country, double-check your culture settings.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload