【问题标题】:.Net razor - While using @Model.Variable name in window.onload - throws reference error.Net razor - 在 window.onload 中使用 @Model.Variable 名称时 - 引发参考错误
【发布时间】:2021-07-27 06:56:37
【问题描述】:

我正在使用带有 Razor 的 ASP.NET Core。 我有一个页面Education.cshtmlEducation.cshtml.cs

Education.cshtml.cs OnGet() 处理程序中,我正在为变量赋值。在.cshtml 文件中,我尝试在window.onload 期间使用@Model.variable 访问变量。在window.onLoad JavaScript 中使用它,因为我必须在页面加载后以这个变量作为参数调用一个 JavaScript 函数。

但我收到一个参考错误:

未捕获的 ReferenceError:未定义“变量值” 在 window.onload

如何解决这个问题下面是我的代码。

在 Education.cshtml.cs 中:

[BindProperty]
public string degree { get; set; }

public async Task<IActionResult> OnGet()
{
    degree = "XYZ";
}

Education.cshtml:

@if (Model.EducationDetails?.successful == true)
{
    <div class="alert alert-success" role="alert">
        <h4>Deatils</h4>
        <hr>
        <strong>@Model.Education.StudentNumber</strong>
     </div>
    <script type="text/javascript">
        window.onload = function () {
         console.log('Model degree value -' + @Model.degree );
        // callJavascriptFunction(@Model.degree); // Need to pass this @Model.degree to JS function
            };
    </script>
}

【问题讨论】:

    标签: javascript c# asp.net-core razor


    【解决方案1】:

    因为你的属性是字符串使用双引号或单引号:

    console.log('Model degree value -' + '@Model.degree');
    

    console.log('Model degree value -' + "@Model.degree");
    

    【讨论】:

    • 不客气!顺便说一句," 字符也应该适用于这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    相关资源
    最近更新 更多