如何将 razor 和 java 脚本结合起来
我想这样做:
@{Session["type"] = $(this).attr("id");}
我这样做了,但出现了错误。
我已经尝试过这个,但它对我不起作用。
using javascript variable in MVC3 Razor view engine
这是我的代码:
$(document).on("click", ".btn-group", function() {
var t = $(this).attr("id");
var text = "@{Session["type"] = "JSVar";}";
text = text.replace("JSVar", t);
});
有人可以给我建议吗?
最佳答案
你不能。在这种情况下,您需要在 Controller 中执行此操作。此外,在 View 中更改 session 值并不是一个好习惯。尝试这样的事情:
public ActionResult ChangeType(int type) {
Session["type"] = type;
}
在你的 JavaScript 中:
$(document).on("click", ".btn-group", function() {
$.ajax({
url: "@Url.Action("ChangeType")",
data: { type: $(this).attr("id") },
});
});
关于javascript - 结合 Razor 和 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015302/