.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

MVC3 Razor - Option to Not have Html encoding

Posted By:      Posted Date: October 04, 2010    Points: 0   Category :ASP.Net

Since all calls to methods (using Razor View Engine and syntax) that return strings have their result Html encoded, is there a way (or an option) to not have the return values html encoded?

For example if I have a simple method like so:

protected string RenderTable(IEnumerable<T> data)
  /* Return some html */

and then in a view (using the Razor View engine) I have code like this:


I'd like the returned string to be inserted into the view as-is and not Html encoded.

What are my options?

View Complete Post

More Related Resource Links

Razor needs shorter syntax to prevent HTML encoding


It's great that Razor HTML encodes by default. However, many times I have HTML in a database and want to display it literally on a page. In WebForms 4, we can use <%= %> and <%: %> to choose between encoding options. Raven's syntax is currently @(new HtmlString(Model.Greeting)). This is far too verbose.

Please add a shorter syntax to Razor. Something like @=Model.Greeting or @@Model.Greeting, or something else.


VS 2010 HTML validation "in CSS" option - where the hell is it?


In VS 2008 there is a very useful feature of background HTML validation - it checks if CSS class name is valid i.e. it exists in one of the linked css files. But VS 2010 Express does not do that any more. And the relevant setting in Options->Text Editor->HTML->Validation->in CSS is not there. Ok, maybe they made it paid for option? VS 2010 Professional? Not there. Or maybe VS 2010 Ultimate? Not a trace.

1. am I blind?

2. they decided it is too convenient to use and removed it?

3. they will "introduce" it in SP1?

What is going on? That one thing made me move back to VS 2008 web developer.


Encoding en Decoding HTML



I stored in a database a ntext "<b>Hello</b>";

But when  I read it from the database I see <b>Hello</b> instead of Hello.

In the html source I see this: &lt;b&gt;Hello&lt;/b&gt;

Any Idea?


Using Dynamic Property inside Html Helper with Razor fires an error



I have the following with Razor:

@Html.GoogleAjax(View.GoogleAjaxKey, new String[,] { { "jquery", "1.4.2" } })

And the I get a strange error:

  'System.Web.Mvc.HtmlHelper<object>' has no applicable method named 'GoogleAjax' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

What is strange is that it works fine using:

@Html.GoogleAjax("123", new String[,] { { "jquery", "1.4.2" } })

I tried the following code line:


And the key is displayed just fine so the problem is how I use the value of @View.GoogleAjaxKey into Html.GoogleAjax.

Do I need to change something on my Html Helper? Here it is:

    public static MvcHtmlString GoogleAjax(this HtmlHelper helper, String key, String[,] libraries) {


Encoding Problems in Razor



On my projects I am using SquisIt Framework and I have the following on page head:


      .Render("~/Styles/FlyOnDreams.FlyOnPages.Core.min.css")) %>

This is working. However when I use Razor view engine I am using the following:


ASP.NET MVC3 Areas and Razor views produce errors?


The view at '~/Areas/SomeArea/Views/List/Index.cshtml' must derive from ViewPage, ViewPage, ViewUserControl, or ViewUserControl.

The project structure is pretty much default. There is one area called SomeArea. It has a single controller called List. It does nothing except:

public ActionResult Index()
    return View("~/Areas/SomeArea/Views/List/Index.cshtml");

The view looks like:

@inherits System.Web.Mvc.WebViewPage<dynamic>
    View.Title = "Index";
    LayoutPage = "~/Views/Shared/_Layout.cshtml";


I have tried emptying the entire file part by part and nothing seems to help. If I create a controller and view outside the area it works just fine. If I create an aspx view it works fine as well. Is it possible the default razor view engine doesn't support areas at this time?

The areas are registered too.

public static void RegisterRoutes(RouteCollection routes)
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters

HtmlHelperExtensions in MVC2 return a HTML string, unencoded. In MVC3 this tring is encoded!

 HtmlHelperExtensions in MVC2 return a HTML string, unencoded. In MVC3 this string is encoded! How can I return unencoded HTML to a Razor view in MVC3? 

MVC3, Razor, and onkeydown

I am trying to create an extension to extend the HtmlTextbox methods to allow our developers to add onkeydown inline javascript to auto click a button with a name they specify.  The relevent code is:... public static MvcHtmlString(this HtmlHelper htmlHelper, string name, string buttonName, object value, IDictionary<string, object> htmlAttributes { if (htmlAttributes == null) { htmlAttributes = new Dictionary<string, object>() } else { if (htmlAttributes.ContainsKey("onkeydown")) { return htmlHelper.TextBox(name, value, htmlAttributes); } } htmlAttributes.Add("onkeydown", string.Format("if (event.keyCode==13) $('#{0}').click();", buttonName)); return htmlHelper.TextBox(name, value, htmlAttributes); } The problem is that the $('btnTest').click() gets encoded to $(#x39;btn#x39;).click(); So, my question is, in razor, how can we ever put these characters in the attributes of a control (wheter it is a textbox, or any other) if it will always get encoded. OR is this a temporary thing (since it is preview 1), and will be fixed?   chad  

Razor. Display conditional Html

Hello,I have the following code on a View using Razor view engine: @if(View.Section == CMSSection.Home) { Html.ActionLink("Home", MVC.CMS.Home.Index()) } else { <span>Home</span> }I keep getting the error:Compiler Error Message: CS1002: ; expectedWhat am I missing?Thank you,Miguel

Data Grid and HTML Encoding Issues, Need Urgent Help


Hi All,

I am facing an issue. I have a datagrid in aspx page. I am binding a dataset data to this datagrid [simple binding]. It works with out any issues. However whenever the data contains any Html tags like 'Test Data With <HTML> tags'
the data in the datagrid cell will show only 'Test Data With <> tags'. The contents inside <> tag will disappear.

My code will look like this.

DataGrid.DataSource = SomeDataSet

I am using C# as the code behind language. Also the data population to the grid is dynamic and depends on the SQL Query used for it. Hence my columns are not predefined. The DataGrid's AutoGeneratedColumns property is True [Number of columns and columns header will change dynamically depending on the query which pulls the data from the DB]

Kindly help with this.

Thanks in advance

MVC3 Beta Razor Views - not partial classes


Why are Razor views not generated as partial classes? Making them partial classes gives us the option to have a code behind where we can do some of the stuff we're forced to do in the template itself in the code behind file.

Yes, I know the standard "go-to" thing is Html helper but I don't want to use Html helpers for these things as they are too specific to the view in question and besides, having a clutter of extension methods is just not the way to go.

I'd like to see Razor views generated as partial classes.

MVC3 Razor - Create a instance of a View


In my controller method, I'm trying to create an instance of a View (cshtml file) before I wrap it around an ActionResult and return it.

Since there is no "class" for Razor Views to speak off, how does one go about creating an instance of a Razor View?

MVC3 beta Razor View Base class/inheritance issues


There seem to be a few issues in the way Razor views are designed and the code generated

1. Descendants of WebViewPage are forced to override Execute() (since it is abstract) but that method is never called. Why?

2. The virtual method ConfigurePage is never called in descendants that override this method.

3. CreatePageFromVirtualPath is no longer virtual. This was the one method that gave us access to the Layout Page (Master Page) instance. Now we no longer have this access. Why was this done?

How can one get access to the instance of a Layout page?

MVC3 Beta @Html.AntiForgeryToken() problem



I am getting strange error when trying to use @Html.AntiForgeryToken() in my views.

The error is:

[ArgumentNullException: Buffer cannot be null.
Parameter name: buffer]
   System.IO.MemoryStream..ctor(Byte[] buffer, Boolean writable) +9638183
   System.IO.MemoryStream..ctor(Byte[] buffer) +6
   System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken) +97

[HttpAntiForgeryException (0x80004005): A required anti-forgery token was not supplied or was invalid.]
   System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken) +397
   System.Web.Mvc.HtmlHelper.GetAntiForgeryTokenAndSetCookie(String salt, String domain, String path) +160
   System.Web.Mvc.HtmlHelper.AntiForgeryToken(String salt, String domain, String path) +16
   System.Web.Mvc.HtmlHelper.AntiForgeryToken() +10

Am I doing something wrong. The request till this exception is raised is GET, not POST. I thought that on GET the token is generated and than is validated on post.

Please advice.<

passing data from a DropDownListFor to Action method in MVC3 (Razor)


I have two questions regarding passing the selection of a dropdownlist to an action method in an MVC controller:


1. What are the options for actually passing the selection back to the action method as a parameter?  The only thing I've been able to get to work is to name the parameter and the select list the same.  For example, my action method looks like:

        public ActionResult Example(int? FeatureId)

// do something with FeatureId
            return View(someobject);

and the static HTML list looks like:


<select name="featureId1">

2.  How can I use an extension method to name the select list appropriately?  I've been trying to do it with the htmlAttributes method but I find that this only works on the id, not the name.  E.g.:



@Html.DropDownListFor(x => x.objects, new SelectList(Model.objects, "FeatureId", "FeatureName"), new { @id = "FeatureId", @name = "FeatureId" })







Razor tooling for MVC3 RC with Visual Studio 2010 Sp1 RTM

Do you see that Razor colorization, intellisense has stopped working after you have installed Visual Studio Sp1 RTM? The reason is that you might have MVC3 RC installed on the box which is not compatible with Visual Studio 2010 Sp1 RTM. To fix, you would need to install MVC3 RTM. Following are the details of the issue. What’s the issue? Razor intellisense/colorization stops working after installing Visual Studio 2010 RTM You might have MVC 3 RC with VS 2010 RTM that’s causing it. How do I check which version of MVC3 do I have? Simple way to check is to verify that the version of ProgramFiles\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll is 3.0.20105.0 If it’s not then most likely you have an older MVC3 build...(read more)

ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series)

This post covers another useful improvement in VS 2010 - HTML/ASP.NET/JavaScript snippet support. Snippets allow you to be more productive within source view by allowing you to create chunks of code and markup that you can quickly apply and use in your application with a minimum of character typing.

Visual Studio has supported the concept of "snippets" for VB and C# in previous releases - but not for HTML, ASP.NET markup and JavaScript. With VS 2010 we now support snippets for these content types as well.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend