我最近和MVC一起工作,在尝试使用ajax向我的控制器发送请求时遇到了一个奇怪的问题.我正在使用直接来自MVC的JQuery(版本1.3.2),我正在尝试发送这样的ajax请求:
$.post("Home/OpenTrade", { price: 1.5 }, function() { }, "json");
Run Code Online (Sandbox Code Playgroud)
我也试过parseFloat("1.5")而不是1.5.
当我尝试在控制器中使用时接收此值
[AcceptVerbs( HttpVerbs.Post)]
public void OpenTrade(float? price)
Run Code Online (Sandbox Code Playgroud)
我的价格总是空的.如果我省略?控制器根本没有调用(这并不奇怪),我尝试使用decimal以及double键入.此外,当我发送整数数据时,此功能有效(如果我发送1此控制器,并且float? price已正确填充).我错过了什么,还是一个错误?
广告.我可以收到价格作为字符串,然后手动解析,但我不喜欢这个解决方案,因为它不优雅,它打击使用像MVC这样的框架为我做这个的整个目的.
编辑和答案:使用Joel的建议,我创建了一个Model Binder,我将发布,也许有人会使用它:
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 …Run Code Online (Sandbox Code Playgroud)