Possible breaking change in MVC4 Razor that can be fixed with "#:#" - asp.net-mvc-3

I recently upgraded my website from ASP.NET MVC3 (Razor) to MVC4 (Razor2), and in doing so found what seemed like a breaking change in the Razor view engine.
The scenario (greatly simplified) is shown below.
#model IEnumerable<string>
#{ Layout = null; }
<!DOCTYPE html>
<html>
<body>
<div>
#foreach (var x in Model)
{
#string.Format("Foo bar: {0}", x) // Errors in MVC4/Razor2
}
</div>
</body>
</html>
This works fine in MVC3/Razor, however in MVC4/Razor2 the string.Format line results in an error of:
Unexpected "string" keyword after "#" character. Once inside code, you do not need to prefix constructs like "string" with "#".
If you remove the #, the view engine then demands that you terminate the string.Format line with a semicolon. However, ReSharper then warns (rightly so):
Return value of pure method is not used.
The two fixes I've found for this are either to use <text>:
<text>#string.Format("The value {0}", x)</text>
Or a more curious approach using #:#:
#:#string.Format("The value {0}", x)
Is this a known and documented change in the Razor view engine?

Seems like a bug. It works with String:
#foreach (var x in Model)
{
#String.Format("Foo bar: {0}", x)
}

This is indeed a bug we decided not to fix, note that the syntax is incorrect as there is no transition between C# and markup in this case.
I understand that resharper shows a warning here but I believe the warning is wrong.
Here is the bug for future reference
https://aspnetwebstack.codeplex.com/workitem/458

Related

How can I add c# code within HTML tags in ASP.Net Core

I'm migrating my site from ASP.net Framework (4.7.2) to Asp.net Core (5). One issue that I can't seem to figure out is that in my original site I had c# in a few of my HTML tags to set the css class(es). For instance:
<div class="carousel-item propertyCarousel #if (firstImage) { <text>active</text> } #if (slideNumber > 2) { <text>bonus-image</text> } " data-slide-number="#slideNumber.ToString("D2")">
Because of tag helpers, asp complains about the code. So I disabled tag helpers in the _ViewImports.cshtml and it no longer complains, but then sometimes the code just doesn't work. For instance in the above example I never get a div with the 'active' class despite verifying the conditions are correct (i.e. that 'firstImage' is true for the first image).
Since the previous commenter did not really answered the question, I'm going to go ahead and say that you need to use brackets for it to work.
This works because it's in a variable:
<div class="#htmlClass"></div>
But when you need the result of an expression from within your HTML attribute like:
<div class="#myvar == true ? "active" : string.Empty"></div>, does not work. What you should do is wrap it in brackets like this :
<div class="#(myvar == true ? "active" : string.Empty)"
This will output: <div class="active"> if the result of the expression was true.

Razor syntax issue with RenderPartial (CS1501)

The RenderAction is working just fine but as soon as I surround it with a if statement I get a compile error:
#if (#Model.IsConfigurationAllow)
{
#{ Html.RenderAction("Save"); } // CS1501: No overload for method 'Write' takes 0 arguments
}
More general question where can I found the grammar for the Razor view syntax?
Html.RenderAction renders the HTML directly into the response, so you cant call it in a code block.
The counterpart Html.Action returns a string with the results.
See http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx
Did you try this?
#if (#Model.IsConfigurationAllow)
{
<text>#{ Html.RenderAction("Save"); }</text>
}
There are a few below (more can be found just by googling);
www.w3schools.com
A quick Reference
Introduction of Using Razor Syntax

Syntax Issue- Razor MVC4

I'm trying to display a partial view using a custom helper method. The only problem is, I can't get past this syntax issue. The model set for this cshtml file is an IEnumerable collection of models I've defined as Operation. I'm sure this is an easy fix. Here's an example of what I'm seeing:
I have this block of code:
#using(Html.BeginForm()) {
<div id="editor_rows">
#foreach (var item in Model){
Html.RenderPartial("OperationEditorRow", item);
}
</div>
}
This gives me the following error at runtime:
Unexpected "{" after "#" character. Once inside the body of a code block (#if {}, #{}, etc.) you do not need to use "#{" to switch to code.
But if I remove the # sign in front of the foreach statement, everything is interpreted as plain text. So I tried placing an # in front of Html as follows:
#using(Html.BeginForm()) {
<div id="editor_rows">
#foreach (var item in Model){
#Html.RenderPartial("OperationEditorRow", item);
}
</div>
}
This comes back with a compilation error that says:
Cannot implicitly convert type void to object
If I run the project from here, I get a runtime error that says:
The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
I'm assuming this is related to the previous error. If anybody has a suggestion for me, please help.
Problem solved. I worked on this with a coworker. It turns out the error refferring to the write method pointed to a problem inside my partial view. I was using #{} around a block of code inside of there, which was most likely throwing the other syntax errors also. Thanks for the responses.
Add {}'s around your render call like #{RenderPartial...}

AntiXss library not working well

I am using AntiXssLibrary 4.0 but it not escaping \x3c. What is my mistake?
I have configure the AntiXss to be a default HttpEncoder based on here http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx and set the encoderType of httpRuntime in web.config.
I also create AntiXSSEncoder derived from HttpEncoder but instead of deprecated
output.Write(AntiXss.HtmlEncode(value));
I use this to override the HtmlEncode method:
output.Write(Encoder.HtmlEncode(value));
Currently if I browse this:
http://localhost:28453/?k=sss\x3cscript\x3ealert%28\x27haaha\x27%29;\x3c/script\x3e
The alert "haaha" shows the AntiXss library is not working. I just want to make like this show http://channel9.msdn.com/Events/MIX/MIX10/FT05 see on the minute 13.
To be confirm I also set this in an action:
public ActionResult Index(string k)
{
ViewBag.k = k;
ViewBag.j = Microsoft.Security.Application.Encoder.HtmlEncode(k);
return View();
}
Then in the view I put this:
<script type="text/javascript">
$(document).ready(function () {
var a = '#ViewBag.k';
var b = '#ViewBag.j';
$('.resultName:first').html(b);
});
</script>
From the browser, the value a and b is the same which is shows the AntiXss does not working well!
<script type="text/javascript">
$(document).ready(function () {
var a = 'sss\x3cscript\x3ealert(\x27haaha\x27);\x3c/script\x3e';
var b = 'sss\x3cscript\x3ealert(\x27haaha\x27);\x3c/script\x3e';
$('.resultName:first').html(b);
});
</script>
Update: It only happened when I use the AntiXssEncoder as encoder type. When I comment this and rebuild. the single quote ' escaped by the MVC. Seems the AntiXss disabled! am I missing something? I want this working because I want like \x3c also escaped like the video.
<!--<httpRuntime encoderType="AntiXSSEncoder, MVCWeb"/>-->
You're right in that, since 4.0 .NET has encoded apostrophes in HTMLEncode, and AntiXSS does not, because, strictly speaking it's not necessary for HTML strings, only for attribute strings.
Now once you swap AntiXSS in as the encoder that assumption no longer applies, and people do, willy-nilly, apply Html encoding everywhere.
So when I push the next version of AntiXSS it will encode apostrophes all the time.

Why is my custom HTML Helper result getting html encoded?

I've got the following custom html helper in asp.net mvc 3
public static string RegisterJS(this HtmlHelper helper, ScriptLibrary scriptLib)
{
return "<script type=\"text/javascript\"></script>\r\n";
}
The problem is that the result is getting html encoded like so (I had to add spaces to get so to show the result properly:
<script type="text/javascript"></script>
This obviously isn't much help to me.. Nothing I've read says anything about this.. any thoughts on how I can get my real result back?
You're calling the helper in a Razor # block or an ASPX <%: %> block.
These constructs automatically escape their output.
You need to change the helper to return an HtmlString, which will not be escaped:
return new HtmlString("<script ...");

Resources