@bobnoordam

MVC – Using icons as standard buttons and submit button

The View

The following markup defines two images as buttons. Standard GET behevaiour is the simple one of the two, it isnt anything else then an image wrapped into a link. The @Url.Action calls the required action on the controller. The submit button is an actual button. The mini CSS snippet makes sure we dont get the default gray background of the button, and only the actual image. The end result is that the two while being technically different, offer the exact same view to the user.

@using (@Html.BeginForm()) {
    <style type="text/css">
        .imageButton {
            background-color: white;
            border: none;
        }
    </style>
    <h2>
        @ViewBag.StatusMessage
    </h2>
    <!-- A 'normal' button is implemented with a simple clickable image that calls an url action-->
    <a href="@Url.Action("ButtonClick")">
        <img src="/Content/Icons/close_45px.png"/>
    </a>
    <!-- A 'submit' button is implemented with an actual button, that contains and image tag -->
    <button type="submit" class="imageButton">
        <img src="/Content/Icons/save_45px.png"/>
    </button>
}

Controller

The controller gives you a feedback message based on the button clicked.

using System;
using System.Web.Mvc;

namespace MVC_Sample.Controllers {
    public class HomeController : Controller {
        public ActionResult ButtonClick() {
            TempData["StatusMessage"] = "You clicked the standard button " + DateTime.Now;
            return RedirectToAction("Index");
        }

        public ActionResult Index() {
            if (TempData["StatusMessage"] != null) {
                ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
            }
            return View();
        }

        [HttpPost]
        [ActionName("Index")]
        public ActionResult IndexPost() {
            ViewBag.StatusMessage = "You clicked the submit button " + DateTime.Now;
            return View();
        }
    }
}