C# 将viewmodel参数转换为json以用于ajax请求
在我的C# 将viewmodel参数转换为json以用于ajax请求,c#,jquery,razor,asp.net-core-2.1,C#,Jquery,Razor,Asp.net Core 2.1,在我的netcore2.1mvc项目中,我有一个viewmodel参数userID,我想在页面加载后将其分配给JQuery变量。该ID不会显示在页面上的任何位置。 到目前为止,这似乎不起作用: 视图: @{int userID = Model.ID;} // rest of html page. @section scripts { <script src="~/AssigntoVariable.js"></script> } 显然,当我运行这个程序时,我会收到
netcore2.1mvc
项目中,我有一个viewmodel参数userID,我想在页面加载后将其分配给JQuery变量。该ID不会显示在页面上的任何位置。
到目前为止,这似乎不起作用:
视图:
@{int userID = Model.ID;}
// rest of html page.
@section scripts {
<script src="~/AssigntoVariable.js"></script>
}
显然,当我运行这个程序时,我会收到一个“UserID not defined”错误。
如何将viewmodel中的userID参数直接放入JQuery脚本中?您可以在客户端访问viewmodel参数
ID
作为userID
,如:
@section scripts {
<script type="text/javascript">
var userID = @(Html.Raw(Json.Encode(Model.ID)));
// You can now access userID here
console.log(userID);
</script>
<script src="~/AssigntoVariable.js"></script>
}
请注意,您不需要使用
$(document).ready(function () {
$(function () {
它们都在AssignToVariable.js
文件中,如$(function(){
只是一个缩写。请使用其中一个
$(document).ready(function () {
var json = userID;
console.log(json);
});
$(document).ready(function () {
$(function () {