I am developing a web application in asp.net mvc 3. I am very new to it. In a view using razor, I'd like to declare some local variables and use it across the entire page. How can this be done?
It seems rather trivial to be able to do the following action:
@bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName); @if (isUserConnected) { // meaning that the viewing user has not been saved <div> <div> click to join us </div> <a id="login" href="javascript:void(0);" style="display: inline; ">join</a> </div> }
But this doesn't work. Is this possible?
Variables are declared using the var keyword, or by using the type (if you want to declare the type), but ASP.NET can usually determine data types automatically.
Declaring (Creating) Variablestype variableName = value; Where type is a C# type (such as int or string ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
The @ symbol is used in Razor initiate code, and tell the compiler where to start interpreting code, instead of just return the contents of the file as text. Using a single character for this separation, results in cleaner, compact code which is easier to read.
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
I think you were pretty close, try this:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);} @if (isUserConnected) { // meaning that the viewing user has not been saved so continue <div> <div> click to join us </div> <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a> </div> }
I think the variable should be in the same block:
@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName); if (isUserConnected) { // meaning that the viewing user has not been saved <div> <div> click to join us </div> <a id="login" href="javascript:void(0);" style="display: inline; ">join</a> </div> } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With