Reputation: 113
I need to use the @(ViewData["value"]);
in document.ready
. But when I use the
@(ViewData["value"])
all jQuery not working. My sample given below:
$(document).ready(function () {
var test = @(ViewData["value"]); // remove this line query has been working
if (test != null){
//my code
}
});
Upvotes: 1
Views: 2706
Reputation: 28695
instead of accessing @(ViewData["value"]);
inside javascript, it's better to put that value inside a hidden field or other element. look at code bellow:
<input id="some-id" type="hidden" value="@(ViewData["value"]);" />
...
...
...
$(document).ready(function () {
var test = $("#some-id");
if (test != null){
//my code
}
});
Upvotes: 3
Reputation: 1021
If your ViewData["value"]
is a string
, you can try this :
var test = '@ViewData["value"]';
Upvotes: 0
Reputation: 4461
If using C# inside script tag you need to enclose the C# variable in quotes. Try
$(document).ready(function () {
var test = '@(ViewData["value"])';
if (test != null){
}
});
If the value of your ViewData["value"] is number it's okay if you don't enclose it in quotes but if it is string with spaces for example ViewData["value"]="Hello World" your browser will get an error saying "SyntaxError: missing ; before statement" that's why your scripts or jquery will no longer work.
Upvotes: 2
Reputation: 15861
ViewData is not accessible on client, because it exists only on view rendering. possible option
Upvotes: 1