這不是標準,所以請在標記重複之前閱讀。從我的MVC應用程序獲取會話值到我的Javascript中
在我們在我們的_Layout.cshtml
頂部MVC應用程序,我們載入我們的腳本是這樣的:
@Scripts.RenderFormat("<script src='{0}' defer></script>", "~/bundles/scripts")
截至_Layout.cshtml
底部,我們有這樣的:
@RenderSection("scripts", required: false)
對於外部原因,我控制我們必須有這個推遲。 :(
這束包括jQuery的文件,其中的其他文件被稱爲Script.js
,它獲取的jQuery後加載,並且有一個名爲setCollapse(collapse)
功能
它看起來像這樣:。
function setCollapse(collapse) {
debugger;
alert(collapse);
if (collapse == 'False') {
$('.collapse').collapse("show");
} else {
$('.collapse').collapse();
}
}
我想用一個會話值,像這樣在我的MVC視圖載荷javascript函數:
@section scripts
{
<script>
$(document).ready(function() {
debugger;
var collapse = '@Session["Collapse"].ToString()';
setCollapse(collapse);
});
</script>
}
但我繼續得到:
Uncaught ReferenceError: $ is not defined
我怎樣才能讓我的會話價值得到傳入我的javascript/jQuery的頁面加載時?
你有沒有正確加載你的jQuery腳本? – Ric
是的,我所有的其他jQuery代碼都可以。事情是,延遲,視圖中的任何JavaScript都會在加載jQuery之前運行。我的script.js文件在jQuery之後被加載,但我不確定如何將Session值存入script.js。 –
儘量不要拖延。只要在使用它之前在頁面中包含jQuery,您的代碼就應該可以工作。 – Shyju