user254197
user254197

Reputation: 881

Use my own c# variable in jquery

how can I use my own c#(MVC5, ASP.NET 4.5.1) variable in jquery ? Something like that:

  $(function () {

        @if (Model != null && Model.Count() > 0){
            int carrier = Model.Count;

        }
        if (location.hash = "#DHLNational") {
            $("#faq-cat-1-sub-0").show(800);
            alert(@carrier);
        }
    });

I get the following error message:

Error 8 "The name 'carrier' does not exist in the current context"

Ok, but if I do it like this:

    $(function () {

        @if (Model != null && Model.Count() > 0){
      int carrier = Model.Count;

      if (location.hash = "#DHLNational") {
          $("#faq-cat-1-sub-0").show(800);
          alert(@carrier);
      }
  }
    });

Visual studio does not understand jquery anymore. Thanks...

Upvotes: 2

Views: 2005

Answers (2)

Sajjad Gholami
Sajjad Gholami

Reputation: 1

First you have to declare and cast C# variables to javascript variables like:

for integer variables :

int carrier = parseInt('@Model.Count');

for string variables :

var myJavascriptString = '@Model.MyCSharpString';

Now you can use your javascript variable.

Upvotes: 0

Guffa
Guffa

Reputation: 700870

You have declared the variable inside the if statement, so it doesn't exist outside that scope. Declare it outside:

$(function () {

  @{
    int carrier = 0; // needs a value, as the next statement might not set any
    if (Model != null && Model.Count() > 0){
      carrier = Model.Count;
    }
  }
  if (location.hash = "#DHLNational") {
    $("#faq-cat-1-sub-0").show(800);
    alert(@carrier);
  }
});

Upvotes: 2

Related Questions