Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using javascript variable in MVC3 Razor view engine

Is it possible?

@Html.ActionLink( "Link text", "Action Name", new { id = *JAVASCRIPT VARIABLE* })

Please explain with example code.

like image 534
Mohammed Faruk Avatar asked Jul 02 '12 03:07

Mohammed Faruk


2 Answers

It actually is very much possible with the following:

var hello = "Great Job!";

var text = "@Html.ActionLink( "Link text", "Action Name", new { id = "JSVar" })"
text = text.replace("JSVar",hello);

As easy as that! :)

All the @Html.Action link does is create a url string so doing replace on it is the same as replace on any javascript string

like image 75
krilovich Avatar answered Oct 23 '22 18:10

krilovich


No it is not possible, because .NET MVC 3 is server side code and is evaluated before being sent to the client, and javascript is Client side code which runs only once it is ON the client

BUT the reverse is possible:

var jsVar = "@yourMvcVar";
like image 31
Darko Z Avatar answered Oct 23 '22 18:10

Darko Z