Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a local variable in Razor?

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?

like image 634
vondip Avatar asked Jul 06 '11 19:07

vondip


People also ask

How do I declare a variable in dot net?

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.

How do you declare a variable in C#?

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.

What is @model in Razor?

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.

What is Razor syntax in MVC?

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.


2 Answers

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> } 
like image 189
Tomas Jansson Avatar answered Sep 28 '22 01:09

Tomas Jansson


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>     }     } 
like image 25
Khasha Avatar answered Sep 28 '22 01:09

Khasha