Hcabnettek
Hcabnettek

Reputation: 12928

How can I output javascript to a view in asp.net mvc3?

Good morning All,

I have a javascript variable in my view. I keep doing this...

 var skinData = null;

and then on document.ready....

 $.ajax({
                type: 'POST',
                url: 'theme/getskins',
                data: {},
                contentType: 'application/json; charset=utf-8',
                success: function(data){
                    skinData = data;
                }
        });

my question is why am I doing this on after the view has loaded. I'm trying to do this in _ViewStart.cshtml

viewPage.ViewBag.SkinInfo = new JsonResult { Data = SkinManager.GetSkins() };

How can I take this value and output its value to my javascript variable. I don't think I need to do another request when I really want to push this to the client on the first trip. Any tips or advice is of course appreciated. How can I do this correctly? I tried a few variations of this but it obvious isn't working. Stuff like...

  var skinData = @ViewBag.SkinInfo.Data;      

This just outputs the namespace. Any ideas how to do this correctly?

Cheers,
~ck in San Diego

Upvotes: 0

Views: 2199

Answers (2)

mdm20
mdm20

Reputation: 4563

Here's a way of doing it using a Html helper. It will convert your object into json and put it into a javascript variable.

HtmlHelper extension method

public static MvcHtmlString Jsonize(this HtmlHelper helper, string variableName, object obj)
{
    StringBuilder str = new StringBuilder();
    str.Append("<script type='text/javascript'>");
    str.Append("var ");
    str.Append(variableName);
    str.Append("=");

    if (obj == null)
        str.Append("null");
    else
        str.Append(JsonHelper.Serialize(obj));

    str.Append(";");
    str.Append("</script>");
    return MvcHtmlString.Create(str.ToString());
}

The json serializer. I'm using the DataContractJsonSerializer in this case.

public class JsonHelper
{
    public static string Serialize(object obj)
    {
        string json = null;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, obj);
            json = Encoding.Default.GetString(ms.ToArray());
        }
        return json;
    }
}

Once you have that done, you can just use it in your views to create a javascript variable that contains your object

@Html.Jsonize("data", ViewBag.SkinInfo.Data);

which will create something like this:

<script type='text/javascript'>
  var data = { your serialized object };
</script>

Upvotes: 3

Mark Coleman
Mark Coleman

Reputation: 40863

You will want to use some a serializer to convert your .GetSkins() method result into a json object. Either the built in JavaScriptSerializer or json.net

JavaScriptSerializer serializer = new JavaScriptSerializer();
viewPage.ViewBag.SkinInfo = serializer.Serialize(SkinManager.GetSkins());

And then in your view

var skinData = @Html.Raw(ViewBag.SkinInfo);

Upvotes: 5

Related Questions