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.TestControl(@<text>function(){ alert("test"); }</text>)
Control Helper:
public static HtmlString TestControl<TModel>(this HtmlHelper<TModel> helper, Func<object, object> onSubmit)
{
var obj = new {onSubmit = onSubmit.Invoke(null) };
var jsonObj = new JavaScriptSerializer().Serialize(obj);
return new HtmlString(string.Format("<script>var obj = {0};</script>", jsonObj));
}
Output:
<script>var obj = {"onSubmit":{}};</script>
Desired Output:
<script>var obj = {"onSubmit": function(){ alert("test"); }};</script>
I can see that the value of obj.onSubmit in the helper is the function... but how can I get the function to serialize and appear in the json object (as a function)?
UPDATE:
Using @<text> to define the anonymous function inline is preferred. We use Kendo controls with this syntax and the goal is to keep the code consistent.
Here is an example on the syntax for kendo controls: http://docs.kendoui.com/api/wrappers/aspnet-mvc/Kendo.Mvc.UI.Fluent/UploadEventBuilder
Based on @ryan's answer, I upgrade a little bit to more like kendoUI.
Here is JsFunctionConverter:
And you can do it like KendoUI
Just make this onSubmit argument being a string and use its value as is. You will no longer need the text tags when calling the helper.
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:
Output:
Now I can call obj.onSubmit() on the client to call the function.
You are confusing a function on the server with a function on the client. You're actually executing onSubmit on the server and the result of that is being put into your object which you serialize into json.
Instead:
Make your 2nd parameter to TestControl a string. Also, don't serialize an object. Instead, create your json manually.
Then you can use:
Your jsonObj will be:
and finally, your
TestControl()
method will return