Returning a PartialView with both HTML and JavaScript

后端 未结 4 498
终归单人心
终归单人心 2021-01-06 15:43

I am making an AJAX call (with jQuery) to retrieve a PartialView. Along with the HTML I\'d like to send back a JSON representation of the object the View is dis

4条回答
  •  生来不讨喜
    2021-01-06 16:30

    I think I found a pretty good way to do this, just wrap the JSON up in an HtmlHelper extension. Here's the class:

    using System.Web.Script.Serialization;
    
    public static class JsonExtensions {
        public static string Json(this HtmlHelper html, string variableName) {
            return Json(html, variableName, html.ViewData.Model);
        }
    
        public static string Json(this HtmlHelper html, string variableName, object model) {
            TagBuilder tag = new TagBuilder("script");
            tag.Attributes.Add("type", "text/javascript");
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            tag.InnerHtml = "var " + variableName + " = " + jsonSerializer.Serialize(model) + ";";
            return tag.ToString();
        }
    }
    

    And you call it via:

    <%= Html.Json("foo") %>
    <%= Html.Json("bar", Model.Something) %>
    

    The one catch that I can think of is that it isn't a completely perfect separation; you are still technically putting JavaScript in the HTML. But, it doesn't make an extra call to the server, and the markup in the IDE is still very clean.

提交回复
热议问题