Changing HTML output in MVC3 - asp.net-mvc

In my MVC3 application I want to remove all HTML5 tags for the output when the user is using IE < 9 to avoid using a frontend workaround.
I've looked in to using a HttpModule, ActionFilter, the OnResultExecuted method on a controller and inside Application_Start.
I've figured so far that I need to get the output as a string from HttpApplication.Context.Response.OutputStream using something like:
HttpApplication application = (HttpApplication)source;
HttpResponse response = application.Context.Response;
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
But all I get is the same error Stream was not readable.
I can write to the response with context.Response.Write.
From reading around on SO and google, MVC doesn't seem to have the same "page life cycle" has webforms(where I'm just overring Render and it works fine) which makes sens.
So my question is how do I get the HTML as a String in MVC? Have anyone tried to manipulate the html output?

I think you should be able to use an ActionFilter to do this. I've seen an example of someone modifying the output stream in this blog post. or in this post.

HTML5 is backwards compatible so feel more than free to use this default output with any browser. Obsolete browsers such as IE6 would still render correctly and even unobtrusive validation is going to work. So my advice is to leave the output as is.

Why dont you use javascript? Just determine what is user browser and remove html you want. JQuery has nice methods to do that.

To follow the concept of the MVC pattern, I'd look to use a different View implementation depending on whether the browser supports HTML 5 or not rather than trying to bodge the output. An alternative would be to use controls through a third party library that can decompose gracefully when the browser doesn't support all the latest features (or the library can implement the controls independently). JQuery, as supplied with ASP.NET MVC is an ideal with many, many controls available that cover most HTML5 tags.

Related

XSS Attack prevention in C#

I've a Web API project which is consumed by an MVC project. The MVC project has a fair amount of user inputs which are displayed as output on the web page.
Now, I want to protect my site from XSS attacks. I've read about Microsoft's AntiXss library, input validations, output filtering etc. But my question is, How do I apply this to my project. Where to put input validations, how to filter my output, how do i sanitize user data, do I need to sanitize the data in APIs also or just in MVC before I send it to the APIs, and if yes, then how, where to use AntiXss library, in MVC or in web API, and how etc.
The answer depends on how exactly user input makes its way into the page DOM in the browser.
If the MVC application generates cshtml pages (with Razor), you need to implement output encoding there, in cshtml files. Note that AntiXSS as a separate library is now deprecated, it's now in the System.Web.Security.AntiXss namespace by default. You need to encode all output according to the context that they get written into (most importantly, you need to encode any input that's written in a Javascript context, be it a script tag, an event attribute like onclick, the first character of a href for an a tag, etc). For plain html output (text between tags) Razor already provides html encoding by default, so it's ok to just do <div>#myVar</div>.
If your frontend consumes something like a JSON API, then you probably have some kind of a client side template engine (Knockout, etc). In that case, it's reasonably safe to send data as received from the user back to the client with an application/json content type (that's actually very important). Then you have to carefully select binding methods to always bind user input as text and not as html to the page elements. This practically means things like using Knockout's text binding instead of html or using jQuery's .text() method instead of .html(), etc.
Please note that a full tutorial on XSS prevention would be way longer than an answer here, so this answer only highlights some high level things and the general way this should be done to prevent XSS.

HTML5 input types and the asp.net MVC Framework

Im looking to make the editor templates in my MVC application use HTML5 input types. The framework seems to get about 80% of the way there but there are a couple of things I can't seem to make happen (step values on numerics, placeholders, URL inputs, etc).
I'm sure that quite a bit of this is just me not knowing where to look, but
Is there a definitive list of what attributes I can use on View Models to provide the metadata used to generate the html?
Does anyone know of a project / nuget package that helps with this? I'm not opposed to writing something, but would rather use something that's already been tried and tested. Dean Hume's ASP.net MVC HTML5 Helpers Toolkit is close, but I'd like to put as much information in the attributes as possible and let the runtime do the work via Html.EditorFor (just a personal preference).
Thanks,
Joe
Check this out : http://weblogs.asp.net/rashid/archive/2010/10/21/integrate-html5-form-in-asp-net-mvc.aspx
See if it can help you get started.

Porting ASP.NET (Telerik) multi-column combobox to MVC.

I need to port the functionality of this one and only one AJAX control to MVC, but given the poor selection of MVC controls out there, I think I need to bring this legacy control into the MVC world...
I'd rather not taint my MVC project with ASP.NET controls, and welcome json/MVC alternatives you know of. (post them if you know of any)
Sample UI that I need in ASP.NET MVC
Back to porting
Although it's unfortunate that I am left to porting this control to MVC, it seems to be a widely accepted practice since Telerik has detailed instructions on how do this.
That makes me ask:
How common is it for a MVC website to use ASP.NET controls?
Again I'll mention I don't want to do this so I welcome MVC-specific alternatives. That being said, I'll proceed with trying to merge that control with my existing site. </End Disclaimer>
If you click on this hyperlink, and look at the source code at the bottom, can you tell me where I should put the following in MVC?
Code behind (My first instinct is to use a Controller but another SO question indicates I should create a create a ViewName.aspx.cs file)
How do I port the SQLDataSource to the new "Model" way of thinking. I know they are different in nature but I don't know how to present data to a ASP.NET control in a way that it will consume the information.
How do I handle the AJAX component? This control has an AJAX component using callbacks. Yes this is getting ugly, but it seems like I have to do this.
Apparently this model saves data in session or view-state. I have no idea if this even work in MVC. Guidance, an alternate control, or a life preserver is much appreciated.
I've already done research and have instructions from Telerik here and here that describes how to get started with placing a simple menu, but I need a little assistance with the more complex controls like this one.
Note: For all the commentary that has hit this question, please remember that I only want this one ASP.NET control functionality; I can't find a comparable control in MVC.
porting from asp.net webforms to MVC is a paradigm shift.
Directly porting does not work.
The Model is where you typically describe your data and do the data access
the View is for displaying the data
The controller plums the other two together
So SQLDataSource is your data access layer and would therefore go to your model
the problem with the thought pattern of SQLDataSource == Model then you get away from the point of decoupling your presentation from data access
You have to think of MVC development as a new build
I would pick a book or video series from your preferred source and learn starting with MVC3 (it has some differences that simplify build speed and reinforce the difference between webforms and mvc)
Hope this helps.
This article explains how to run web forms and mvc together
http://weblogs.asp.net/rajbk/archive/2010/05/11/running-asp-net-webforms-and-asp-net-mvc-side-by-side.aspx
This is by telerik and explains the limitiation of the grid and what is need to get it to run.
http://blogs.telerik.com/aspnetmvcteam/posts/08-11-06/asp_net_ajax_controls_in_asp_net_mvc.aspx
Add an IFrame in your MVC view that just shows the WebForms page (or just use that control on a single WebForms page).
There is nothing that says you can't have a site with both WebForms and MVC pages. You can route a single URL to a WebForm just for this control.
Why not just use the telerik MVC controls? They work quite well. Either get them via a NuGet package or visit this link http://www.telerik.com/products/aspnet-mvc.aspx
I would rather use ViewModel instead of code behind
You don't have to throw away SqlDataSource you can use result set and buld from it your model, problem may be column names in result set... tricky but can be done
Since there is no components in MVC except helpers youll need help of jQuery probably, it easy
$.ajax({
url : "/controller/action",
data: { /*json or serialized form */ },
successs: function(data){
//if you got response as html from /controller/action
$("#some_div").html(data);
}
}
Session is available in MVC but viewstate not, you can use HttpContenxt.Cache or TempData if you need something like viewstate. USe TempData to keep data between redirections, or httpcontext.cache to cache your data further more.
I can't find similar functionality in an MVC control
MVC doesn't really have a concept of controls in the same way that ASP.Net does - there are only really the plain old HTML controls (i.e. hidden input, text input, checkbox, radiobuttons, select box, text area, password and buttons).
When you need something more complicated than the plain HTML Controls you need to use some JavaScript to achieve this.
I'm not sure that you will be able to 'port' the control into MVC - you will most likely have to try and re-create it your self using an MVC controller and a partial view with a fair bit of a javascript to create the control.
Have a look at the JQuery UI Autosomplete plugin - you could probably use this to acheive something similar

What's the best way to develop a debugging window for an ajax ASP.Net MVC application

While developing my ASP.NET MVC, I have started to see the need for a debugging console window to assist in figuring out what is going right and wrong in my code. I read the last few chapters of the Pro Asp.net MVC book, and the author details how to use http modules to show page load/creation times and linq to sql query logs, both of which I definitely want to be able to see. However, since I am loading a lot of small sections of my page individually with ajax I don't want the debug information right there in the middle of my screen.
So the idea I came up with was to have a separate browser window (open-able by a link or some javascript) with a console log, that can contain logged entries both from javascript and from the asp.net mvc run. The former should be relatively easy, but I'm having trouble coming up with a way to log the asp.net information in ajax requests.
The direction I have been thinking of going is to create an httpmodule (like the Pro MVC book does), and have that module contain some script tags that append the javascript's log to console calls with the messages. The issue I see with this is finding a way to get the log messages from the controller's action methods to the httpmodule's methods. The only way I see to do this is with a singleton, but I'm not sure if singletons are bad practice for a stateless web application.
Furthermore, it seems like if I return json with my ajax calls (instead of pure html) then that won't work at all unless there is a way to add data to an existing json structure inside the httpmodule.
How does everyone else handle this type of debugging in heavily ajax applications?
For reference, the javascript library I am using is jquery.
Why not Firebug or Fiddler? (or both? Together they do 99% of what you need.)

Do you use any custom ASP.NET MVC HtmlHelper extensions?

I'm interested in seeing what custom extensions other developers have created for the ASP.NET MVC HtmlHelper class.
I think Microsoft got off to a great a start, but as usual, left a lot of open holes to fill!
Looks like I am going to have to create some for rendering images, rendering action links as images, and so on.
Thought it might be beneficial to actually put a list together and save some other developers some time and effort, and I'll be honest, save me some time as well. =)
If you have any website links to other extension methods for the HtmlHelper class please provide them!
You should check the MVC-Contrib project on Codeplex...
Also, I just found this paging extension to the HtmlHelper which looks pretty cool, although I've not used it yet.
I wrote an article about building custom controls in ASP.NET MVC, and I actually use the "Rollup Grid View" that I built in there.
I wrote a post to gather useful MVC HtmlHelpers and share them with others; we can grow it up!
Take a look: http://sharplife.net/2008/11/14/UsefulHtmlHelpersForASPNETMVC.aspx (or http://tinyurl.com/mvchelper to remember easily!).
I made quite a few for a project I did at work. The ones that I can think off the top of my head were:
ActionImage, which was the unholy love child of ActionLink and Image.
ScriptBlock, which could write out a JavaScript script block based on some parameters from the ASP.NET.
Textile, which would take a string marked up in Textile markup and write out that markup as XHTML produced by a Textile library.
There were a few other more specific ones as well, but I think it's a really neat way of encapsulating blocks of tags.

Resources