VALIDATEINPUTATTRIBUTE CHANGES IN MVC3

November 8, 2010 § Leave a comment

VALIDATEINPUTATTRIBUTE CHANGES IN MVC3

The ValidateInputAttribute has received a nice little tweak in MVC 3 offering more fine grained control over parameters of a request.

In MVC 2 using ValidateInputAttribute was limited to the request level, that is all parameters in the request where either validated or not.  Lets demonstrate this with a simple example – a simple forum posting page,

<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<Common.Model.ForumPost>” %>
<asp:Content ContentPlaceHolderID=”TitleContent” runat=”server”>
Login
</asp:Content>
<asp:Content ContentPlaceHolderID=”MainContent” runat=”server”>
<h2>Post Question</h2>
<% using (Html.BeginForm()) { %>
<p>
<%=Html.LabelFor(c => c.Subject)%>
<%=Html.TextBoxFor(c => c.Subject)%>
</p>
<p>
<%=Html.LabelFor(c => c.Body)%>
<%=Html.TextAreaFor(c => c.Body)%>
</p>
<input type=”submit” value=”Post” />
<%} %>
</asp:Content>

We don;t care what the controller actions actually do but lets describe them here anyway

public class HomeController : Controller
{
    public ActionResult Post()
    {
        return View();
    }
[HttpPost]
    public ActionResult Post(ForumPost post)
    {
        return View();
    }
}

Now attempting to post any sort of markup back to the action will result in an exception being thrown,

If we wanted to allow markup to go through we can add the [ValidateInput(false)] attribute to the action.  The only problem with that is if we only wanted to allow markup in the Body and not the Subject we would have to write our own tests in the controller to prevent this.  Not the most ideal or clean solution.

MVC 3 solves this quite simply by extending the ValidateInputAttribute and allowing use to specify exclusions.  This means we can have validation turned on but specifically state the we don’t want to validate a specific request parameter(s) (e.g. Body).

[ValidateInput(true, Exclude = "Body")]

A very minor tweak that makes a big leap to being able to produce cleaner more readable code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

What’s this?

You are currently reading VALIDATEINPUTATTRIBUTE CHANGES IN MVC3 at Naik Vinay.

meta

%d bloggers like this: