【发布时间】:2015-10-07 07:38:06
【问题描述】:
我有一个 mvc 4 应用程序。 在其中一个帖子操作中,我希望有一个“对象”类型的参数。 它应该能够接受来自客户端的数字、字符串以及通用 json。
我尝试使用以下模型绑定器来实现它:
public class ObjectModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
{
return null;
}
else
{
var js = new JavaScriptSerializer();
var result = js.Deserialize<object>((string)value.ConvertTo(typeof(string)));
return result;
}
}
}
在客户端中,我使用 jquery ajax 发布数据,如果值是 javascript 对象,我使用 JSON.stringify。
当我发送 json 或 int 时,它可以工作,但如果我尝试发送字符串,它会抛出异常 - “无效 JSON 原语:THE_STRING_VALUE”
我应该使用其他东西吗?
感谢您的帮助。
【问题讨论】:
-
你要发送什么字符串?
标签: c# json asp.net-mvc-4