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

前端 未结 4 1465
被撕碎了的回忆
被撕碎了的回忆 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:31

    I spent more time searching around and found similar posts but didn't see a solution:

    Serializing a function as a parameter in json using C#

    JSON serializing an object with function parameter

    Finally got it to work using the Json.net library. Using the JRaw class will generate a json object with the onSubmit property defined as a function.

    Json.net documentation: http://james.newtonking.com/projects/json/help/html/SerializeRawJson.htm

    Updated Control Helper:

    public static HtmlString TestControl(this HtmlHelper helper, Func onSubmit)
    {
        var obj = new { onSubmit = new JRaw(onSubmit.Invoke(null).ToString()) };
        var jsonObj = JsonConvert.SerializeObject(obj);
        return new HtmlString(string.Format("", jsonObj));
    }
    

    Output:

    
    

    Now I can call obj.onSubmit() on the client to call the function.

提交回复
热议问题