Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing server side mvc variables to javascript [closed]

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.

like image 335
amateur Avatar asked Feb 11 '13 22:02

amateur


1 Answers

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))
like image 127
Declan Cook Avatar answered Oct 20 '22 01:10

Declan Cook