Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generic syntax inside a Razor view file?

I was trying to use the following statement:

@Html.Test<ISQL>().Nand() 

However, Razor is choking at the < before the ISQL.

Any official work around for it?

like image 502
kidoman Avatar asked Nov 23 '10 06:11

kidoman


People also ask

How can you comment using Razor syntax?

Comments Razor View Engine has two types of comments, one is single-line and another is multiline. Razor uses the syntax "@* .. *@" for the comment block but in a C# code block we can also use "/* */" or "//".

How do you declare a string variable in Razor view?

To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.

Can you use Razor syntax in JavaScript?

You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser. It's meant to be executed server-side.


Video Answer


2 Answers

To use generic methods you need to escape the expression

@(Html.Test<ISQL>().Nand()) 
like image 105
marcind Avatar answered Oct 25 '22 13:10

marcind


I just found this question when I was looking for this "same error" when upgrading mvc.

I had :

Does not work:

@{     ViewBag.Title = "Something " + @Model.Title;    var something = (IEnumerable<SelectListItem>)ViewBag.Options;     } 

Apparently, the syntax went stricter, and as you are inside a @{} block, you should not add @ before Model.Title on the example. But the error on the code editor was pointing to the generic and it was getting me crazy.

It works fine if there is no <> inside the code, but just removing the @ from Model.Title fix the issue.

Works:

@{     ViewBag.Title = "Something " + Model.Title;    var something = (IEnumerable<SelectListItem>)ViewBag.Options;     } 

Hope this helps to anyone

like image 31
Juan Carrey Avatar answered Oct 25 '22 11:10

Juan Carrey