User279_1
User279_1

Reputation: 113

Jquery not working in cshtml page

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

Answers (4)

Habibillah
Habibillah

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

andri
andri

Reputation: 1021

If your ViewData["value"] is a string, you can try this :

var test = '@ViewData["value"]';

Upvotes: 0

Jobert Enamno
Jobert Enamno

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

Ravi Gadag
Ravi Gadag

Reputation: 15861

ViewData is not accessible on client, because it exists only on view rendering. possible option

  1. serialize your view data to json on server side
  2. write it to hidden field, and them parse it to javascript object on client side.

Upvotes: 1

Related Questions