I haven't posted in a while do to being busy with my new job, but I thought I'd just share this code snippet.
In the new asp.net mvc framework, you often have the need for a single form, but multiple buttons that each post to a different controller action. In webforms you didn't have to worry about this as all forms did a postback and asp.net created event wiring magic to wire up each button to an event handling method. But with MVC, we're forced to go a little old school. So I created a little helper method that I'll probably submit to MvcContrib or something if they don't have one like this already. It lets you wire up controller methods to each submit button in a strongly typed fashion using lambda expresssions.
Here's an example:
<% using (Html.BeginForm())
{ %>
<h2>About</h2>
<p>
Put content here.
<%= Html.SubmitButton<HomeController>(x => x.DoSomething(), "Do something now")%>
<%= Html.SubmitButton<HomeController>(x => x.DoSomethingElse(), "Do something else")%>
</p>
<% } %>
Obviously the generic parameter above called "HomeController" is the controller class and the DoSomething() is the method in that class. I also let you specify the button label and optionally the name of the button and other html attributes.
Here's the source code:
public static class SubmitHelper
{
public static string SubmitButton<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string buttonText) where TController : Controller
{
var name = buttonText.Replace(" ", ":");
name = "SUBMIT_BUTTON:" + name;
return SubmitButton<TController>(helper, action, name, buttonText);
}
public static string SubmitButton<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string name, string buttonText, IDictionary<string,object> dictionary) where TController : Controller
{
return helper.SubmitButton(name, buttonText, dictionary );
}
public static string SubmitButton<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string name, string buttonText) where TController : Controller
{
var link = LinkBuilder.BuildUrlFromExpression<TController>(helper.ViewContext.RequestContext, helper.RouteCollection, action);
var dictionary = new Dictionary<string,object>();
dictionary.Add("OnClick", "this.form.action = '" + link + "';");
return helper.SubmitButton(name, buttonText, dictionary);
}
}
For this to build, you must reference the Microsoft.Web.Mvc dll and namespace, which can be found here:
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471or click below to download directly:
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471#DownloadId=61773Enjoy!