简体   繁体   English

将数据从Ajax发布到控制器后未调用自定义JSON转换器

[英]Custom JSON converter not being called after posting data from ajax to controller

I have implemented this custom json converter to convert types depending on the data received, but it seems like it's never being called. 我已经实现了这个自定义json转换器,以根据接收到的数据转换类型,但是似乎从未调用过它。 Is the action doing the native parsing and my converter is not being used? 该动作是否在进行本机解析,并且未使用我的转换器?

My results are posted into this action 我的结果已发布到此操作中

[HttpPost]
public JsonResult saveCustomfields(CustomFields customfields)
{

}

Model 模型

public class Field
{
    public string _label { get; set; }
    public string _name { get; set; }
    public string _type { get; set; }
    public List<Option> option { get; set; }
}

public class Fields
{
    [JsonProperty("field")]
    [JsonConverter(typeof(SingleOrArrayConverter<Field>))]
    public List<Field> field { get; set; }
}

public class Formtemplate
{
    [JsonProperty("fields")]
    public Fields fields { get; set; }
}

public class CustomFields
{
    [JsonProperty("formtemplate")]
    public Formtemplate formtemplate { get; set; }
}

Custom converter 定制转换器

public class SingleOrArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Ajax 阿贾克斯

<script>
    jQuery(document).ready(function ($) {
        var fbTemplate = document.getElementById('fb-template');
        var formBuilder = $(fbTemplate).formBuilder();

        $(".form-builder-save").click(function (e) {
            e.preventDefault();
            var x2js = new X2JS();
            var xml = formBuilder.data('formBuilder').formData;
            var json = x2js.xml_str2json(xml);

            alert(JSON.stringify(json));

            $.ajax({
                url: "saveCustomfields",
                type: "POST",
                data: JSON.stringify(json),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
            });
        });
    });
</script>

Disclaimer: This isn't a direct answer, but an alternative solution 免责声明:这不是直接答案,而是替代解决方案

So the reason I saw this a potential solution is because of this C# attribute: 因此,我看到此潜在解决方案的原因是由于以下C#属性:

[JsonConverter(typeof(SingleOrArrayConverter<Field>))]
public List<Field> field { get; set; }

I'm reading this as a single item or array converter to a list. 我将其作为单个项目或数组转换器读取为列表。 So this is really easy in JavaScript. 因此,这在JavaScript中确实很容易。

So there is a nifty little trick with JavaScript using the literal and instanceof 因此,使用文字和instanceof JavaScript有一个不错的小技巧

if (!(field instanceof Array)) { // if field isn't an array
   field = [field]; // make it one
} 

This basically says, if the variable ain't an array, then make it one. 这基本上就是说,如果变量不是数组,则将其设为一个。

This may be easier to do then to get C# to fiddle around with the JSON. 然后,使C#与JSON混在一起可能会更容易做到。

Also in my eyes, i believe you should always be communicating the simplest JSON between client and server (and visa versa). 同样在我眼中,我相信您应该始终在客户端和服务器之间交流最简单的JSON(反之亦然)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM