Since .NET 2.0 Asp.net webforms has protected the programmer from cross-site scripting by validating all input sent to the server. Unfortunately, this does not happen in Asp.net mvc. I tested my application by typing 'alert("xss");' surrounded by script tags in the first name textbox. The form saved successfully and I got a javascript alert box with the message "xss".
In asp.net mvc it is the programmers responsibility to validate all input. Calling Request.ValidateInput() in a controller tells the framework that any values read from the request should be validated. If an invalid character is found a HttpRequestValidationException is thrown.
Here is an example implementation:
Request.ValidateInput();
try { UpdateModel(b, new[] { "FirstName", "LastName", "Email" }); }
catch (HttpRequestValidationException) { /* Handle request validation error */ }
This is a simple technique I recently started using to clean up MVC views.
Here was my first attempt at rendering a list of alerts:
<table class="tabTable">
<tr>
<th></th><th>VEHICLE</th><th>ALERT TYPE</th><th>WHEN</th><th>ACT</th>
</tr>
<%
foreach (FleetAlertDTO alert in ViewData.Model)
{
%>
<%= Html.RenderUserControl("~/Views/Alert/FleetAlert.ascx", alert) %>
<%
}
%>
</table>
I didn't like it because there are to many <% %>. Using Response.Write() can help eliminate much of the switching between html and C#. Here is what I ended up with.
<table class="tabTable">
<tr>
<th></th><th>VEHICLE</th><th>ALERT TYPE</th><th>WHEN</th><th>ACT</th>
</tr>
<%
foreach (FleetAlertDTO alert in ViewData.Model)
{
Response.Write(Html.RenderUserControl("~/Views/Alert/FleetAlert.ascx", alert));
}
%>
</table>
It's a simple change, but I think it is much more readable.