如何让JavaScript提醒Razor变量?

时间:2014-02-12 16:31:23

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

我正在尝试创建一个表标题,在单击时会提醒其文本。我无法将Razor变量传递给JavaScript函数参数。什么是好的解决方法?

这是我的代码:

@foreach (var web in Model.Webinars)
{
    var title = web.Filename;
    if (!String.IsNullOrEmpty(title))
    {
        // If filename is too long, shorten it
        if (title.Length > 10)
        {
            title = title.Substring(0, 10) + "...";
        }
        // Create a header that alerts when clicked
        // Errors if I pass @title in alert()
        <th onclick="alert(@title)">@title</th>
    }
}

我收到的错误如下:

JavaScript critical error at line 71, column 34 in 
http://localhost:64023/Webinar/Reports\n\nSCRIPT1010: Expected identifier

2 个答案:

答案 0 :(得分:3)

您需要在引号中包含@title

<th onclick="alert('@title')">@title</th>

答案 1 :(得分:1)

我认为@ Satpal的答案是正确的一半,你需要在引号中包含@title,比如

<th onclick="alert('@title')">@title</th>

但您还需要将<th>包裹在<table>元素中,如下所示,否则它仍无效。

<table>
    <th onclick="alert('@title')">@title</th>
</table>