我习惯让我的Razor视图中直接写下以下脚本: -
$(document).ready(function () {
$("#DCSort").click(function () {
$("#progressSort1").show();
$.ajax({
type: "Get",
url: "@Url.Action("Index","Server")",
data: { searchTerm: "@ViewBag.searchTerm.ToString()", page: "1", sort: "@ViewBag.DCSortPam" },
//contentType: "application/json; charset=utf-8",
//dataType: "json",
//cache: false,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#ServerTable").html(data);
$("#progressSort1").hide();
}
function errorFunc() {
alert('error');
}
})
$("#RackSort").click(function () {
$("#progressSort2").show();
$.ajax({
type: "Get",
url: "@Url.Action("Index","Server")",
data: { searchTerm: "@ViewBag.searchTerm.ToString()", page: "1", sort: "@ViewBag.RackSortPam" },
//contentType: "application/json; charset=utf-8",
//dataType: "json",
//cache: false,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#progressSort2").hide();
$("#ServerTable").html(data);
}
function errorFunc() {
alert('error');
}
})
});
但是为了在多个地方使用这个脚本,我将上面的脚本移到我的Scripts文件夹下的Script文件中。但之后我开始遇到一些语法错误,例如在;"@Url.Action
上。所以我收到这些错误,因为这些是Razor语法? ,以及如何替换“@ Url.Action和其他具有正确的JavaScript语法?
感谢
答案 0 :(得分:0)
您可以在.cshtml文件的底部进行映射
像:
<script>
var searchTerm = @string.Format("{0}",ViewBag.searchTerm),
</script>
然后替换@ ViewBag.searchTerm.ToString();在你的JS中使用searchTerm。并在映射下面放置对外部JS的引用。
答案 1 :(得分:0)
在javascript / jquery中对razor语法应用单引号。
url: '@Url.Action("Index","Server")'
这样做:
$.ajax({
type: "Get",
url: '@Url.Action("Index","Server")',
data: { searchTerm: '@ViewBag.searchTerm',
page: "1",
sort: '@ViewBag.RackSortPam' },
success: function(response)
{
},
error: function(response)
{
}
});
与ViewBag的情况相同:
data: { searchTerm: '@ViewBag.searchTerm',
page: "1",
sort: '@ViewBag.RackSortPam' }