0

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

2
  • What is SkinManager.GetSkins(), is it a .NET object, a string perhaps? Commented Apr 7, 2011 at 16:53
  • No, its a .NET DataContract class with properties Commented Apr 7, 2011 at 17:26

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

this outputs it incorrectly. Using entities instead of quotes... var skinData = {"CookieExpiration":3650,"CookieName":& etc...
See update, try using @Html.Raw so there is not automatic encoding.
3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.