【问题标题】:How to pass MVC View Session In Script如何在脚本中传递 MVC 视图会话
【发布时间】:2018-09-27 18:00:42
【问题描述】:

我有一个 mvc 控制器,在 Controller 中处理 Session 中的所有 Azure Api 密钥并在视图中传递它。

public ActionResult Index()
{
    Session["azureappkey"] = "xxx-xxxx-xxx-xx"; // pass to view
    return View();
}

在视图中:

<h2>Index</h2>

<p> @HttpContext.Current.Session["azureappkey"];</p> // got the session value working as expected
@{ 
    var x = HttpContext.Current.Session["azureappkey"];    // not working assign to variable and pass inside the script
    <script>
        alert(this.x);
        alert (x); // GETTING UNDEFINED
    </script>
}

Azure 应用密钥写在段落标记中,但未在脚本部分定义。

任何人都可以更正实施。

【问题讨论】:

  • 有什么问题吗?什么不工作?
  • 我在段落标签或 dom 中获取会话值,当我在变量 x 中分配并在脚本块内传递时,我无法获取值。如何将其存储在变量中并在其他区域内重新使用可见。
  • 您正在尝试混合使用 C# 和 JavaScript。一般来说,你不想这样做。
  • 当我们使用模型并分配给脚本内的变量时它是如何工作的
  • &lt;script&gt;var x = @Html.Raw(Json.Encode(HttpContext.Current.Session["azureappkey"];)); alert (x); &lt;/script&gt;

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 asp.net-mvc-5


【解决方案1】:

您当前使用的块是 Razor 块而不是 JS 块,并且您将会话状态内容分配给 C# 变量而不是 JS 变量(请参阅下面的范围):

// Razor block
@{ 
    var x = HttpContext.Current.Session["azureappkey"]; // C# variable
    <script>
        alert(this.x); // JS variable with "undefined" state
        alert (x); // x is also undefined, because it not assigned yet
    </script>
}

传递会话状态变量的正确方法是在&lt;script&gt;标签内使用@Html.Raw

<script>
    var x = '@Html.Raw(HttpContext.Current.Session["azureappkey"])';

    alert(x);
</script>

如果 Azure API 密钥包含 JSON 字符串格式,请将 Json.Encode 放入 @Html.Raw 助手中,如 Stephen 所说:

<script>
    var x = @Html.Raw(Json.Encode(HttpContext.Current.Session["azureappkey"]));

    alert(x);
</script>

工作示例:DotNET Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    相关资源
    最近更新 更多