1

I have ASP.NET MVC Project. I am calling one stored procedure in my controller and taking that result into my viewdata like this :

 var sp = callsp(parameter1, paramter2)

 if(abovespcontainsnoresult)
 {
       viewdata["result"] = "This sp doesn't consists any results";
    }

Now I have to pass this to my script function. I have script which enables button when i select list from dropdown :

  $(document).ready(function () {
     $("#button").change(function (e) {

         if ($(this).val() != '')  {
             $("#button1").attr('disabled', false);
             $("#button2").attr('disabled', false);
             $("#button3").attr('disabled', false);
             $("#button4").attr('disabled', false);
         }
      }

Now what I want to do is add viewdata result to this script and check whether it is null or not. I tried like this :

 $(document).ready(function () {
     $("#button").change(function (e) {

          if ($(this).val() != '' &&  ($(@ViewData["result"].ToString()) != "")) 
        {
             $("#button1").attr('disabled', false);
             $("#button2").attr('disabled', false);
             $("#button3").attr('disabled', false);
             $("#button4").attr('disabled', false);
         }
      }

But script doesnt work if I add this condition. So how do I check viewdata result into my script and check whether it is null or not ?

Ajay
  • 317
  • 2
  • 12
  • 25
  • possible duplicate of [ASP.NET MVC using ViewData in javascript](http://stackoverflow.com/questions/5863094/asp-net-mvc-using-viewdata-in-javascript) – JasonWilczak May 02 '14 at 13:00

2 Answers2

2

If you put ticks it will work.

 '@ViewData[result]'

If it is an external JS file (script is not coded in view) it will not work

CSharper
  • 5,420
  • 6
  • 28
  • 54
2

Store the value of $(ViewData["result"].ToString()) to a JavaScript variable, and then use that variable in the if statement.

$(document).ready(function () {
    $("#button").change(function (e) {
        var result = $('@ViewData["result"].ToString()');

        if ($(this).val() != '' && result !== '') 
        {
             $("#button1").attr('disabled', false);
             $("#button2").attr('disabled', false);
             $("#button3").attr('disabled', false);
             $("#button4").attr('disabled', false);
         }
      }

You were on the right track initially.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154