1

I have the following code in a view (Demo.aspx) within a ASP.NET MVC 2 project:

Demo.aspx:

<% if (!Model.IsValid) { %><%= Model.FirstName %> - <% } %><%= Model.LastName %> -

I am trying to convert it to razor view (Demo.cshtml) in the process of migrating the project from ASP.NET MVC2 to ASP.NET MVC3. After doing some analysis and following the URL: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/ for migration of the webforms to razor view, I drafted the following code equivalent in razor view:

Demo.cshtml:

@if (!Model.IsValidName)
        { @Html.Raw(Model.FirstName)
            @Html.Raw("-")
        }
        @Html.Raw(Model.LastName)
        @Html.Raw("-")

But by using the conversion tool : http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790 , I got the following code:

Demo.cshtml:

@if (!Model.IsValidName)
           { @Model.FirstName
        @Html.Raw("-")
         } @Model.LastName
        @Html.Raw("-")

Can anyone help to confirm which of the above is correct?

3
  • Fields used in the generated code seem to have nothing to do with your actual model Commented Aug 6, 2014 at 10:07
  • both are correct but second one is better.. Commented Aug 6, 2014 at 10:14
  • Thanks for your reply. I take your answer (Second answer) based on the fact that Razor expressions are automatically HTML encoded. Correct me in case I am wrong. Commented Aug 6, 2014 at 10:18

1 Answer 1

1

I would recommend the second approach:

@if (!Model.IsValidName)
           { @Model.FirstName
        @Html.Raw("-")
         } @Model.LastName
        @Html.Raw("-")

The reason for this is for security purposes.

As an example the @Model.FirstName will prevent against an XSS attack where as @Html.Raw(Model.FirstName) is circumventing the encoding and making it possible if a user is allowed to update their own FirstName property.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.