How to serialize a function to json (using razor @)

前端 未结 4 1499
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 14:07

How can I serialize a client function to a json object? (similar to how kendo controls work)

This is what I have so far...

View:

@Html.TestCo         


        
4条回答
  •  孤独总比滥情好
    2021-01-14 14:21

    Based on @ryan's answer, I upgrade a little bit to more like kendoUI.

    public class TextBox : BaseControl
    {
        [JsonProperty("onChange", NullValueHandling = NullValueHandling.Ignore)]
        [JsonConverter(typeof(JsFunctionConverter))]
        public Func OnChange { get; set; }
    
        public override MvcHtmlString Render()
        {
            // Create html
            // 
            _tagBuilder = new TagBuilder("input");
    
            // Add script
            StringBuilder builder = new StringBuilder(base.Render().ToString());
            string script = @"";
    
            BuildOptions();
            builder.AppendFormat(script, Name, JsonConvert.SerializeObject(this));
            return MvcHtmlString.Create(builder.ToString());
        }
    

    Here is JsFunctionConverter:

    public class JsFunctionConverter : JsonConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
        }
    
        public override bool CanRead
        {
            get { return false; }
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof (string) || objectType == typeof (Func);
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JRaw jRawData;
    
            if (value.GetType() == typeof(Func))
            {
                jRawData = new JRaw(((Func)value).Invoke(null));
            }
            else
            {
                jRawData = new JRaw(value);
            }
    
            jRawData.WriteTo(writer);
        }
    }
    

    And you can do it like KendoUI

    var textBox = new TextBox
    {
        OnChange = @
                        function(e){
    
                                return e;
                        }
                    
    };
    

提交回复
热议问题