25

Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First

Here is my very simple Script

<script class="TractsScript">

     $('#Add').click(function (e) {

         var val = @ViewBag.ForSection;
         alert(val);

     });
</script>

As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model.

I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer

Other Things i have tried:

var model = @Html.Raw(Json.Encode(Model))
alert(model.Sections);
alert(@ViewBag.ForSection);
Community
  • 1
  • 1
Don Thomas Boyle
  • 3,055
  • 3
  • 32
  • 54
  • If you don't have any circular references in your model, you might try something like `var val = @new JavaScriptSerializer().Serialize(Model)`. – Johan Sep 18 '13 at 12:54
  • Is this script in line into the View? – Fals Sep 18 '13 at 12:55
  • @Fals I'm sorry I'm still new to all of this, if you are asing if the script is in the same document as the View, then yes. – Don Thomas Boyle Sep 18 '13 at 12:57

5 Answers5

32

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);
James
  • 80,725
  • 18
  • 167
  • 237
  • if I ran `var attTwo = '@ViewBag.ForSection';` and then `alert(attTwo);` I receive an Alert with "" (*Null*) value. – Don Thomas Boyle Sep 18 '13 at 12:58
  • Like I said "*It depends on the type of data you are setting*" - what type of data is `ForSection`? – James Sep 18 '13 at 12:59
  • It is set in my Controller and For my `Viewbag.` should be of type `Integer`. My Model.Sections However is parsed to String. – Don Thomas Boyle Sep 18 '13 at 13:01
  • sorry man still not working error: `CS0103: The name 'Viewbag' does not exist in the current context` when using `var vals = parseInt('@Viewbag.ForSection');` and if i write the same code without `@` i get result `NaN` – Don Thomas Boyle Sep 18 '13 at 13:09
  • In Fal's answer he isn't using the `'` around the Variable. This worked thanks for your help +1 – Don Thomas Boyle Sep 18 '13 at 13:18
  • @DonThomasBoyle I thought you would have to wrap it in `'` as `parseInt` expects a string! I wasn't in front of a computer so couldn't test. – James Sep 18 '13 at 13:23
  • 1
    I found James's answer to be correct. I had an integer id in my view bag. var mystrid='@ViewBag.id', var myintid=@ViewBag.id. mystrid had no value, myintid had the integer value for id. – Haim Katz Aug 26 '18 at 12:46
27

You can do this way, providing Json or Any other variable:

1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:

ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });

2) In the View, put the script like this at the bottom of the page.

<script type="text/javascript">
    var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
    alert("Number is: " + number);
    var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
    alert("Text is: " + model.Text);
</script> 
Fals
  • 6,813
  • 4
  • 23
  • 43
  • But when I am trying to access @ViewBag.Number it is showing blank value.. – Hrishikesh T T Jul 12 '17 at 09:54
  • @HrishikeshTT Are you sure you are at the same controller context? Viewbag lives only with the same context of the controller and the called view. – Fals Jul 12 '17 at 13:53
  • Yes I am sure that the script call is in the same controller context. And another doubt is, can we access ViewData in the same manner ? – Hrishikesh T T Jul 13 '17 at 06:40
5

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

Thas
  • 63
  • 1
  • 4
2

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
esi
  • 21
  • 1
0

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);
Johan
  • 35,120
  • 54
  • 178
  • 293