Using keywords in asp.net mvc3 views

Go To StackoverFlow.com

1

I am using MVC3 framework to design a website. I pull the data in the controller from the ms sql database and one of the columns in the table is named as "do". When I try to create a view to display the information using the @Model keyword (eg: @Model.do) , I get an error:

Identifier expected; do is a keyword.

I want to know if there is a way to use the column names ( which are keywords in c#) in the MVC3 views or do I only have the choice of renaming the column in the database table ?

Thank You !!

2012-04-05 21:28
by Learner


2

The way you use any keyword in C# is to prefix it with an '@'. For example, you'll see this a lot

@Html.ActionLink("My Link", "Action", null, new {@class="abc"}) 

to add "class" attribute to a "a" tag. This is legitimate code:

class Program
{
    static void Main(string[] args)
    {
        Entity e = new Entity();
        e.@do = 10;
    }
}

class Entity
{
    public int @do
    {
        get;
        set;
    }
}

and so is

public void DoSomething(int @do)
{
    for (int i = 0; i < @do; i++)
    {
        // process i
    }
}

If you are using ASPX as your view engine, the following is fine:

<%= Model.@do %>

In Razor view, the following is also valid:

@Html.Raw(Model.@do)

or

@(@Model.@do)
2012-04-06 06:01
by bloudraak
+1, good point about escaping keywords using the @ symbol - Travis J 2012-04-06 07:44


1

There is not a way to define the variable do inside of a viewmodel (.cs class).

"Error 1 Invalid token 'do' in class, struct, or interface member declaration"

That being said, you can remap in your model so that the column do is mapped to the field do_field

public class Entity
{
 [Column("do")]
 public string do_field { get; set; }
}
2012-04-05 21:35
by Travis J
Thank you for the reply. Although I am using the Entity Framework model to access the database, I can still do remapping in it - Learner 2012-04-05 21:40
@Learner - That is correct. The model you define which is used by EF can have this data annotation in it. Or, you may use fluent api (http://msdn.microsoft.com/en-us/library/hh295844(v=vs.103).aspx) to define the mapping - Travis J 2012-04-05 21:42
This answer isn't correct. See my answer - bloudraak 2012-04-06 06:12
@WernerStrydom - It is correct in that the error displayed for using a keyword is shown, and how to remap the entity is shown. I did not realize the @ could be used as an escape property like that so the only incorrect statement here is more incomplete in that, as your answer states, you can escape keywords with the @ symbol - Travis J 2012-04-06 07:43
@TravisJ I think you gave good advice. My response was directed at your very first statement - bloudraak 2012-04-06 08:01
@WernerStrydom: I tried your suggestion of escaping the keywords and it works really good . Thank You for giving an alternative solution for the problem ! - Learner 2012-04-06 19:05
Ads