I create a variable and function in view, how to get outer variable inside function ?
@{
var myUrl = "https://example.com";
@functions{
private string ReplaceDomain(string replaceStr)
{
// Can't resolve symbol `myUrl`
return myUrl.Replace("ABC", replaceStr);
}
}
}
<div>
My view
@ReplaceDomain("HAPPY")
@ReplaceDomain("BIRTHE")
@ReplaceDomain("DAY")
</div>
Always show "Can't resolve symbol myUrl
" in function.
Is there any way to get outer variable directly?
Not like following method (not get variable directly)
@{
var myUrl = "https://example.com";
@functions{
private string ReplaceDomain(string myUrl, string replaceStr)
{
// Can't resolve symbol `myUrl`
return myUrl.Replace("ABC", replaceStr);
}
}
}
<div>
My view
@ReplaceDomain(myUrl, "HAPPY")
@ReplaceDomain(myUrl, "BIRTHE")
@ReplaceDomain(myUrl, "DAY")
</div>
CodePudding user response:
You can directly define method in razor view, just change your code like below:
@{
var myUrl = "https://example.com";
string ReplaceDomain(string replaceStr)
{
return myUrl.Replace("ABC", replaceStr);
}
}
<div>
My view
@ReplaceDomain("HAPPY")
@ReplaceDomain("BIRTHE")
@ReplaceDomain("DAY")
</div>