在jquery中使用我自己的c#变量

时间:2014-07-28 13:34:45

标签: jquery asp.net variables asp.net-mvc-5

如何在jquery中使用自己的c#(MVC5,ASP.NET 4.5.1)变量?这样的事情:

  $(function () {

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

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

我收到以下错误消息:

  

错误8“当前上下文中不存在名称'carrier'”

好的,但是如果我这样做的话:

    $(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不再理解jquery了。 感谢...

2 个答案:

答案 0 :(得分:2)

您已在if语句中声明了该变量,因此它不存在于该范围之外。在外面声明:

$(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);
  }
});

答案 1 :(得分:0)

首先,您必须声明C#变量并将其转换为javascript变量,例如:

对于整数变量:

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

对于字符串变量:

var myJavascriptString = '@Model.MyCSharpString';

现在您可以使用您的javascript变量。