MVC 3 to MVC 4 Razor Compiler Error

76 Views Asked by At

I am getting a runtime error, saying that I am missing a closing paren. The error occurs on the line where I set emailText

This code works in MVC 3 but not MVC 4. I know the new Razor is more strict but syntactically this code still looks right. All parens match, etc.

Any ideas?

 @if (Model.Counselors != null)
   {
                for (var i = 0; i < Model.Counselors.Count; i++)
                {
                    string counselorDivId = "counselorname" + i.ToString();
                    string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + @counselorDivId + "\" data-attr-id=" + @Model.Counselors[i].Id + " style=\"float:right;\"></a>";
                    string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
                }
    }
3

There are 3 best solutions below

1
On

try

    @(if (Model.Counselors != null)
       {
            for (var i = 0; i < Model.Counselors.Count; i++)
            {
                string counselorDivId = "counselorname" + i.ToString();
                string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + @counselorDivId + "\" data-attr-id=" + @Model.Counselors[i].Id + " style=\"float:right;\"></a>";
                string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
            }
})
0
On

It appears to be an issue with the last line that starts with "string emailText ...". For some reason razor does not like the less than sign in your ternary statement. When I switched it around to be a greater than sign, then it looks like it worked. I am not sure if this is a bug in razor or not.

0
On

Strangely, but I guess logically, nested "@" blow up MVC 4/Razor 2. By removing the nested "@" prefixes, the code was successfully parsed and executed

@if (Model.Counselors != null)
       {
                    for (var i = 0; i < Model.Counselors.Count; i++)
                    {
                        string counselorDivId = "counselorname" + i.ToString();
                        string deleteLink = "<a class=\"icon delete counselor\" data-attr-divid=\"" + counselorDivId + "\" data-attr-id=" + Model.Counselors[i].Id + " style=\"float:right;\"></a>";
                        string emailText = (!String.IsNullOrEmpty(Model.Counselors[i].CounselorContactEmail) ? (Model.Counselors[i].CounselorContactEmail.Length < 29 ? Model.Counselors[i].CounselorContactEmail : "Email " + Model.Counselors[i].CounselorContactName) : "");
                    }
        }