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

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

    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.

    public static HtmlString TestControl(this HtmlHelper helper, string onSubmit)
    {
      string jsonObj = String.Format("{{ \"onSubmit\": {0} }}", onSubmit);
      return new HtmlString(string.Format("", jsonObj));
    }
    

    Then you can use:

    @Html.TestControl("function(){ alert('test'); }")
    

    Your jsonObj will be:

    { "onSubmit": function(){ alert('test'); } }
    

    and finally, your TestControl() method will return

    
    

提交回复
热议问题