【问题标题】:MVC 4 .net send generic object (not necessarily json)MVC 4 .net 发送通用对象(不一定是 json)
【发布时间】: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


【解决方案1】:

问题在于 JSON 一个字符串,因此您需要能够区分 JSON 字符串和非 JSON 字符串。试试这样的:

    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
        {
            int n;
            string s = (string)value.ConvertTo(typeof(string));
            if (s.StartsWith("{") || s.StartsWith("["))
            {
                var js = new JavaScriptSerializer();
                var result = js.Deserialize<object>(s);
                return result;
            }
            else if (int.TryParse(s, out n))
            {
                return n;
            }
            return s;
        }
    }

【讨论】:

    猜你喜欢
    • 2016-06-22
    • 2017-01-15
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多