MVC 3 to MVC 4 Razor Compiler Error

67 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 answers

1
Rick james 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
user1408767 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
Slinky 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) : "");
                    }
        }