4

Is there a way to pass the Model data to external javascript without having hidden variables on my View. I am using Google map to display pushpins and the map is loaded via javascript and at the same time I have (big)list of latitude, longitude information as a part of my Model data which is fetched during my request. I do not want to have a long list of hidden variables in my html and also reduce one more ajax call to the server to fetch the required information(lat/lon) in my javascript. Is there any way to do this efficiently?

Thanks.

1 Answer 1

1

The short answer is "no."

If you need to return a raw data model alongside your view, the only option is to embed the data in the view. The two options are:

In an HTML element (kind of awkward IMO):

<div id="myData" data-model="{&quot;Name&quot;: &quot;Jason&quot;}"></div>

In script:

<script>
  var myData = {Name: Jason};
</script>

I prefer the second method as there is no HTML escaping.

I agree it is kind of annoying to have to do this, but one request is one request... it is just one stream of data. Bootstrapping data in this way is fairly common, so maybe a future version of MVC will have a cleaner way to return it (but it would probably look just like one of my examples above).

Outside of that, as you mentioned, you can do an extra request to receive just the model in a JSON response.

EDIT:

I had a HtmlHelper up my sleeve to help with this...

public static MvcHtmlString ToScriptVariable<T, TMember>(this T value, Expression<Func<T, TMember>> expression) where T : class 
{
    var member = expression.Body as MemberExpression;
    if (member == null)
        throw new ArgumentException("Expression must be a member expression.", "expression");

    var expressionValue = expression.Compile()(value);
    var serializer = new JavaScriptSerializer();
    var seralizedData = serializer.Serialize(expressionValue);

    var tag = new TagBuilder("script");
    tag.Attributes.Add("type", "text/javascript");
    tag.InnerHtml = String.Format(CultureInfo.InvariantCulture, "var {0} = {1};", member.Member.Name, seralizedData);

    return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

Usage:

<%: Html.ToScriptVariable(x => Model.MyData) %>

Result:

<script type="text/javascript">var MyData = "(whatever)"</script>
Sign up to request clarification or add additional context in comments.

2 Comments

There are other two option check this and this post. Hope help someone.
Nice approach, but I like also the links @stom provided, because they show what else is possible. +1 for you both!

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.