Archive for the ‘patterns’ Category
The Visitor Pattern, Double Dispatch and Reflection Performance
Was listening to Herding Code #70 this morning and heard the Visitor Pattern mentioned. It was new to me (in theory but not in practise) so I was led merrily down the garden path.
Background and definition of the Visitor Pattern.
An example of the visitor pattern in C# using double-dispatch and reflection.
Naming Your Action Methods in ASP.Net MVC
Something that I always do now and might in fact be quite obvious to regular people but I’m quite slow so it took me a little while to realise this was a good practise.
Let’s say I have a page for editing a blog post. I want the form to be at /BlogManagement/Edit/postId.
So I write my first action method:
public ActionResult Edit(int ID)
And here’s what the URL looks like in my browser:
Cool. Now I write the method for the edit form view to post to:
public ActionResult UpdateBlogPost(FormCollection formData)
{
…
}
This will work of course. But what happens if validation fails? We get send back to the edit form. But we don’t want to redirect, we’ll just return the appropriate view and viewdata. So what will the URL be now?
Oh dear. That’s no good at all. Now our visitors have this erroneous entry in their history. No, this will not do.
To tidy this up we’ll make use of method overloading and the AcceptVerbs action method attribute. Here’s the signature of the GET action method which displays the edit form view:
[AcceptVerbs(HttpVerbs.Get)]
[Authorize(Roles = "administrator")]
public ActionResult Edit(int ID)
{
and here’s the signature of the POST action method that validates, updates and redirects:
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
[Authorize(Roles = "administrator")]
public ActionResult Edit(FormCollection formData)
{
This works because the ASP.Net MVC routing engine understands method overloading and, providing you are using the AcceptVerbs attribute, it will route each request to the appropriate method.
Doing this will make sure that the URL in the browser stays the same during the whole process. Much neater, no?
