Writing C# Code in MVC Razer Layout Page – How to

If you intend to write C# code in your MVC Layout Page, I am talking about MVC 4 here, this is quick tutorial + a couple of odd behaviors that one should know.

Example: You want to declare a variable and use it to render or not render a particular html code

Solution:

@{String name ;
name = Model.Student.Name.ToString(); // lets assume this is comming from model

if name = "admin")
{

You are Administrator

} else {

You are regular user

} }

Notice here, the big @{ } where all code is encompassed. Notice that { } is required after the if statement. Also notice that dash(-) is not allowed in variable names in Layout Page, which is really weird. Also notice that comments with @ { // comments } are typical C# comments but comments outside the @{} block should be html comments

CS1002: ; expected MVC 4

If you get the following error and get figure out what in the world is causing this error, problem could be you are using dash(-) in variable name. The error message is counter intuitive.

CS1002: ; expected // in MVC 4 C#

Remove dash from variable name and everything should be fine. This is a weird error.

This entry was posted in Tutorials/Tips. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s