ASPNET MVC: Handling Multiple Buttons on a Form with jQuery

Sometimes your task in MVC involves many buttons in the same form. Such as the screen shot here.

What happens in most situations is that you end up having some code that kind of looks like this:


<form action="/foo/save">

<!-- My HTML and multiple buttons -->

</form>

… and then the code looks like this


public ActionResult Save(CustomerList customers, string buttonName)

{

if(buttonName == "Save")

{

// do something

}

else if (buttonName == "Reload")

{

// etc, etc

}
// Other if's, etc, etc

}

We can solve this with a little jQuery. By attaching a click handler to the button we can tell the form where we want it to go. Therefore keeping our controllers actions very slim.

Here’s the jQuery:


// This assumes your buttons have id's "save-button" and "update-button"

$("#save-button").click(function () {

 // Redirect to add facility for Credit Exposure
 var form = $(this).parents('form:first');
 form.attr('action', '<%=Url.RouteUrl(new { controller = "foo", action = "save"  }) %>');
});

$("#reload-button").click(function () {

 // Redirect to add facility for Credit Exposure
 var form = $(this).parents('form:first');
 form.attr('action', '<%=Url.RouteUrl(new { controller = "foo", action = "reload"  }) %>');
});

Now when the user clicks “Save” they will go to the “Save” Action on the “FooController”. When the user clicks “Reload” they will go to the “Reload” action on the”FooController”. No more logic switches in the Controller.

You can download and example here (minus the MVC Goo):

jQuery Tip: Brute Force Dirty Form Detection

If you disable your “save” button on your MVC views when the page first loads and want them to be auto-enabled when any input on the form changes, you can do that with the following jQuery snippet.

This is sort of a hack*, but it works.

With this HTML


<input type="submit" id="myButton" value=" Save " disabled />

and this javascript:


<script>
 $(function () {
$(":input").change(function () {
// if any input element changes, enable the save and undo buttons
$("#<%=myButton.ClientID %>").removeAttr('disabled');
});
 });
</script>

You’ll “enable” the button when the form inputs are changed. This is kind of nice when you have a TON of inputs on the page and you need to be able to detect when ANY of them have changed.

* Why its a Hack: I’m not limiting the selector to an ‘id’ therefore sizzle scans the entire DOM which could be a bummer in regards to performance).

No IE6 ActionFilter for ASP.NET MVC

*** Update ***: I’ve also created a cheap jQuery plugin for this as well. See the bottom of the post

There’s a lot of talk on Twitter today about IE6. I’m building a web application in my free time and I didn’t want to support IE6. Will I lose users? Yes, a few, but I don’t care. To try to help circumvent someone with IE6 hitting my site I wrote an ASP.NET MVC Action Filter to block anything less than IE7. It’s rather crude, but it works.

Please note, I’ve only tested this with IE Tester, so real IE6 users… well YMMV.

Here’s the code:


public class NoIe6Attribute : ActionFilterAttribute
 {

 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
 var browser = filterContext.HttpContext.Request.Browser.Browser;
 var major = filterContext.HttpContext.Request.Browser.MajorVersion;

 if(browser.ToLowerInvariant() == "ie" && major <= 6)
 {
 filterContext.Result = new ContentResult {Content = Ie6NotSupportedHtml};
 }

 }

 public string Ie6NotSupportedHtml
 {
 get
 {
 return @"<html>
<head>
 <title>IE6 Not Supported</title>
 <style>

 body {
 background-color: #111;
 color: #FFF;
 font-family: Trebuchet MS, 'Helvetica Neue', Arial, sans-serif;
 font-weight: light;
 letter-spacing: 1px;
 line-height: 1.5;
 }

 h1 {
 font-size: 60px;
 font-weight: bold;
 line-height: 1;
 margin: 40px 10px 10px;
 text-align: center;
 }

 h2 {
 font-size: 20px;
 font-weight: normal;
 line-height: 1.2;
 margin-bottom: 20px;
 margin-right: 10px;
 margin-left: 10px;
 text-align: center;
 }

 a:link,
 a:visited,
 a:hover,
 a:focus,
 a:active {
 border: none;
 color: #5EA9FF;
 font-weight: bold;
 letter-spacing: 1.5px;
 text-decoration: none;
 }

 .container {
 margin: 0 auto;
 width: 540px;
 }

 </style>
 </head>
 <body>
 <divcontainer>
 <h1>Sorry, we do not support IE6.</h1>
 <h2>Please <a href=""http://www.microsoft.com/ie"" target=""_blank"" title=""Upgrade IE"">upgrade your browser</a> to a recent version of Internet Explorer</h2></div>
 </body>
</html>";
 }
 }

 }

Explaining It

It’s crude, but so it IE6, so we’re fighting fire with fire here. You don’t need to include any fancy HTML or whatever. If this filter finds that you’re running IE6, it will change the ViewResult to a ContentResult and stuff some hard-coded HTML into that result.

Result

This is what you’ll see if you visit an action/controller/etc that is decorated with this attribute. (click for bigger image)

How to Use It

Personally I like to block _all_ IE6 access (for my current project), so I throw it on my BaseController (the class all of my controllers inherit from). You can also slap it on an action, or you can slap it on a single controller if you’re doing some wonky stuff in an individual controller.


[NoIe6]
public class HomeController : Controller
{
 public ActionResult Index()
 {
 ViewData["Message"] = "Welcome to ASP.NET MVC!";

 return View();
 }

}

// or on an action

public class HomeController : Controller
{
 [NoIe6]
 public ActionResult Index()
 {
 ViewData["Message"] = "Welcome to ASP.NET MVC!";

 return View();
 }

}

Enjoy.

Let me know if you see any errors with it. I whipped it up a few weeks ago and never touched it since.

Update

jQuery Plug-In

Some people said they would rather have this as a jQuery plug-in. I understand that, but I still prefer to go on the server side. That way I don’t get the entire HTML of the page sent back to the user. They get what I give them when they use IE6. However, not everyone thinks like me. So here is a jQuery plugin for it.

Download the Plug-in: jquery.noie6.js

Code:


/**
 * jQuery noie6
 * A jQuery plugin to display text for IE6 Users.
 *
 * v0.0.1 - 31 March 2010
 *
 * Copyright (c) 2010 Donn Felker (http://twitter.com/donnfelker)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 *
 * Use $.noie6();
 *
 **/
;jQuery.noie6 = function (x) {
 // Stolen from thickbox
 if (typeof document.body.style.maxHeight === "undefined") {
 $("body").html("<style>        body {background-color: #111;color: #FFF;font-family: Trebuchet MS, 'Helvetica Neue', Arial, sans-serif;            font-weight: light;            letter-spacing: 1px;            line-height: 1.5;        }        h1 {    color:#FFF;        font-size: 60px;            font-weight: bold;            line-height: 1;            margin: 40px 10px 10px;            text-align: center;        }        h2 {    color: #FFF;        font-size: 20px;            font-weight: normal;            line-height: 1.2;            margin-bottom: 20px;            margin-right: 10px;            margin-left: 10px;            text-align: center;        }        a:link,        a:visited,        a:hover,        a:focus,        a:active {            border: none;            color: #5EA9FF;            font-weight: bold;            letter-spacing: 1.5px;            text-decoration: none;        }        .container {            margin: 0 auto;            width: 540px;        }    </style><div class=\"container\">        <h1>Sorry, we do not support IE6.</h1>        <h2>Please <a href=\"http://www.microsoft.com/ie\" target=\"_blank\" title=\"Upgrade IE\">upgrade your browser</a> to a recent version of Internet Explorer</h2>    </div>");
 }
};

Usage:


<script>

$(function() { $.noie6(); }

</script>

This will give you the same screen I showed above (black background, white text, etc). However, this will not get run until document.ready _and_ you will have a whole goop of HTML that came down with the page. Note: The browser detection is from some Thickbox code.