Multiple submit buttons in asp.net MVC

In asp.net MVC you can submit a form by @using(Html.BeginForm()). You can Post the model you have binded via this operation and command the begin form to post to a Post action:   @using(Html.BeginForm("Create","FooController")).

Now if you have more than one submit button to send the page content to different post action, there are few ways: one of them is to post the content to a specific action and then decide in it to redirect which action:

 Razor:

  1. <input type="submit" value="Field1" name="submitButton"  />
  2. <input type="submit" value="Field2" name="submitButton"  />

 

Controller:

 

  1.          public ActionResult SpecificOne(DTO dTO, string submitButton)
  2.          {
  3.                 switch (submitButton)
  4.                 {
  5.                     case "Field1":
  6.                             return RedirectToAction("FirstCreate")
  7.                     case "Field2":
  8.                               return RedirectToAction("SecondCreate")
  9.                  }
  10.           }

 

 

But the way that I like it more is to use attribute in post actions, this attribute would be like this:

 

  1.    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  2.     public class HttpParamActionAttribute : ActionNameSelectorAttribute
  3.     {
  4.         public string Name { get; set; }
  5.  
  6.         public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
  7.         {
  8.             return controllerContext.HttpContext.Request[Name] != null;
  9.         }
  10.     }

 

 

Now in your razor view you should give name to your buttons (names should be the same as your target actions) :

  1. @model DTO 
  2. @using(Html.beginForm(null, null))
  3. {
  4.    <button type="submit" name="FirstCreate" >First</button>
  5.    <button type="submit" name="SecondCreate" >Second</button>        
  6. }

 

And about the actions you should use the mentioned attribute and give the button name property:

  1.         [HttpPost]
  2.         [HttpParamAction(Name = "FirstCreate")]
  3.         public ActionResult FirstCreate()
  4.         {
  5.             return View();
  6.         }
  7.  
  8.  
  9.         [HttpPost]
  10.         [HttpParamAction(Name = "FirstCreate")]
  11.         public ActionResult SecondCreate()
  12.         {
  13.             return View();
  14.         }

 

 

Good luck!


Tags: C# Asp.Net MVC


comments powered by Disqus