9

I am looking at feedback as to the best and easiest way to pass server side variables from a controller action to the sites html markup and for them to be used then by javascript on the site.

I am working with asp.net mvc4 and trying to find the recommended method of doing such.

2
  • 3
    google search gives tons of results... Commented Feb 11, 2013 at 22:24
  • 3
    @emrenevayeshirazi: <sarcasm>Oh, what a useful comment on Stack Overflow!</sarcasm> Commented Oct 14, 2014 at 13:53

1 Answer 1

20

You have a couple of options.

One is attach data-attributes or id's to elements and fetch them using javascript.

Using razor views:

<div id="someid" data-name="@item.attribute"></div>

JS:

$('#someid').data('name')

Or you can render the data directly into a script tag.

Using razor:

 var somevar = "@item"

You can also Json.Encode more complex objects.

 var somevar = @Html.Raw(Json.Encode(object))
Sign up to request clarification or add additional context in comments.

4 Comments

Also to emphasize Declan's answer, if you use the var somevar = "@item"; method you MUST wrap it in the quotes as he has, failing to do so could yield a statement that reads as var somevar = ;. This may seem straight forward for strings and such, but is less obvious when dealing with nullable booleans, nullable integers, etc.
I'd recommend the first approach (in a div- or hidden input-tag) for better separation of content and code. The minute you need to introduce a <script>-tag in a .cshtml file, you're doing something wrong.
Off - For those who use webform : use var somevar = "<%=item%>";
I would say that the best way is data-attr because you don't have any dependencies to have script in your UI code. function Service() { this.data = $("...").data('info'); }; var service = new Service(); Service.prototype = { doSomething: function() { alert(this.data()); } }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.