Blog

Filter posts by Category Or Tag of the Blog section!

Multiple submit buttons in asp.net MVC

Monday, 09 June 2014

In asp.net MVC you can submit a form by @using(Html.BeginForm()). You can Post the model you have bound via this operation and command the beginning 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:

<input type="submit" value="Field1" name="submitButton"  />

<input type="submit" value="Field2" name="submitButton"  />

 

Controller:

         public ActionResult SpecificOne(DTO dTO, string submitButton)

         {

                switch (submitButton)

                {

                    case "Field1":

                            return RedirectToAction("FirstCreate")

                    case "Field2":

                              return RedirectToAction("SecondCreate")

                 }

          }

 

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

   [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class HttpParamActionAttribute : ActionNameSelectorAttribute

    {

        public string Name { get; set; }



        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)

        {

            return controllerContext.HttpContext.Request[Name] != null;

        }

    }

 

 

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

@model DTO 

@using(Html.beginForm(null, null))

{

   <button type="submit" name="FirstCreate" >First</button>

   <button type="submit" name="SecondCreate" >Second</button>        

}

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

        [HttpPost]

        [HttpParamAction(Name = "FirstCreate")]

        public ActionResult FirstCreate()

        {

            return View();

        }





        [HttpPost]

        [HttpParamAction(Name = "FirstCreate")]

        public ActionResult SecondCreate()

        {

            return View();

        }

 

Good luck!

Category: Software

Tags: Asp.Net

comments powered by Disqus