0

I am using C# asp.net mvc3. In one of my views, say I declare a variable like this:

@{
    ViewBag.Title = "title"   
    string mystr;  
}

I need to set the value of the variable mystr in a function of the script. How do I access this variable from the script? Suppose I have a function like

<Script type="text/javascript">
function(){
    var st = "This string is for the global variable"
     mystr = st;
}
</script>

mystr will later be used in the html code like this: <h2>@mystr</h2> . Is there a similar way of accessing a variable from a function?

4

1 回答 1

0

mystr在您的示例中是在视图解析期间存在的服务器端变量。cshtml所以你不能用客户端的 JS 代码来影响它。你可以尝试这样的事情:

<script type="text/javascript">
window.mystr = @(mystr); // Set value while server side processing.
function(){
    var st = "This string is for the global variable"
    window.mystr = st; // Get/Set value
}
</script>

并在您需要的任何地方使用客户端的全局变量mystr

如果您需要然后通过 JS 设置标题的文本,您可以使用 jQuery 进行设置:

<h2 id="header"></h2>

JS:

$('#header').text(window.mystr);
于 2012-11-02T19:30:36.343 回答