Friday, December 30, 2011

Implementing Cancel button functionality in ASP.NET MVC 3

Implementing a Cancel button functionality - currently I cannot imagine a better topic for my first blog post ever. And no matter how trivial the topic is, I am sure there is plenty of room left for me to slip somewhere.

I am a huge fan of ASP.NET Web Forms framework. I love the stateful Web model approach and yes – I am not afraid of postbacks, I am using viewstate and I think I could not live without server side controls and code-behind in my web pages.

And now I am trying to fall in love again with ASP.NET MVC. Which is not an easy task for me, but I am moving on.

While playing around with my ASP.NET MVC application I came across a situation where I needed to implement a simple data entry form. It had some text fields on it, a Save button to submit entered information and a Cancel button which would just redirect to an index page. The problem for me was – how to implement cancel button functionality?

One of the possible solutions is presented by Andrey Shchekin (Multiple submit buttons with ASP.NET MVC: final solution). This could work, but I don’t want to have the complete MVC page life cycle being triggered just for a cancel button functionality. More than that - I don’t even want to make Cancel button as a submit button because I don’t want validation of my form to be triggered while clicking it.

Solution I found suitable for me is simple: 

<input type="submit" value="Save" />
<input type="button" value="Cancel" 
       onclick="javascript:document.location.href='@Url.Action("Index", "Home")'" />

6 comments:

  1. 'Are you sure you want to cancel... All your data will be lost.' How about some kind of functionality when the cancel button was clicked. And of course this makes sense just if there were added some values, if the user doesn't changed the form, this functionality doesn't make sense.

    ReplyDelete
  2. Thank you! Your solution worked perfectly for my scenario. Thank you thank you thank you :)

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Great! This is exactly what I was looking for! I just changed some stuff to fit my interface.

    ReplyDelete
  5. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete
  6. Great blog you have written for us Thanks for sharing good content keep sharing... check it once through MSBI Online Training Hyderabad for more information on microsoft.

    ReplyDelete