Question

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 !!

Was it helpful?

Solution

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)

OTHER TIPS

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; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top