MVC3 to MVC4 RTM Manual Upgrade issue: @ in front

2019-03-31 02:47发布

问题:

I have a MVC3 project that has the following line of code which worked just fine:

@if (this.Model.ShowAddButton)
{ 
    @this.Html.ActionLink("Add", "Add")
}

Our team has a coding guideline that all local method calls need to be prefixed with this. This has worked just fine in MVC3 up until now.

I've manually upgraded the project to MVC4, using the guidance from here. Now the code above errors out with the following message:

Unexpected "this" keyword after "@" character.  Once inside code, you do not need to prefix constructs like "this" with "@".

I think the error message is misleading. It implies that it is legal to do this, but not necessary. I am purposely doing this even though I know it is not needed to adhere to coding guidelines. The fact the parser fails, the message should indicate Once inside code, you cannot prefix.... I understand you can't use @ in nested code blocks, and the issue isn't with the @ sign, but the use of this. Adding this to the statement doesn't affect the result of the call, so I don't understand why it is throwing an exception. I can fix the issue by removing this:

@if (this.Model.ShowAddButton)
{ 
    @Html.ActionLink("Add", "Add")
}

But doing this will conflict with our coding guidelines. So my question is, is this something that was purposely changed in MVC4 (since it worked just fine in MVC3). Or is this a bug in MVC4? If I remove the if block, I can still use the this keyword.

@this.Html.ActionLink("Add", "Add")

回答1:

This is in fact a bug in MVC4. A report was filed.

The two work arounds are:

@if (this.Model.ShowAddButton)
{ 
    @Html.ActionLink("Add", "Add")
}

OR

@if (this.Model.ShowAddButton)
{ 
    @(this.Html.ActionLink("Add", "Add"))
}