Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

A Razor view has 3 buttons inside a form. All button's actions will need form values which are basically values coming input fields.

Every time I click any of buttons it redirected me to default action. Can you please guide how I can submit form to different actions based on button press ?

I really appreciate your time, guidance and help.

share|improve this question
    
show us some code please... what have you tried? probably, from the question jquery might come in handy for you.. – now he who must not be named. Oct 29 '13 at 5:43
    
Its not directly possible to do what you have asked, but with a workaround, check this link – AthibaN Oct 29 '13 at 5:55
    
please show us your snippet – Lamloumi Afif Oct 29 '13 at 8:20
    
up vote 46 down vote accepted

You could also try this:

<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />

Then in your default function you call the functions you want:

if( Request.Form["submitbutton1"] != null)
{
    // Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
    // code for function 2
}
share|improve this answer
    
wouldn't this make the submit buttons show the label as "submit1" etc? – BerggreenDK Mar 13 '14 at 19:44
1  
The question isn't about the labels. But yes, in this example the buttons will be labeled submit1 and submit2 – Jeroen Dop Apr 16 '14 at 9:39
    
@BerggreenDK: you can use <button> instead of <input> if you need different labels. – Pavel V. Jan 22 at 11:44

This elegant solution works for number of submit buttons:

@Html.Begin()
{
  // Html code here
  <input type="submit" name="command" value="submit1" />
  <input type="submit" name="command" value="submit2" />

}

And in your controllers' action method accept it as a parameter.

public ActionResult Create(Employee model, string command)
{
    if(command.Equals("submit1"))
    {
      // Call action here...
    }
    else
    {
      // Call another action here...
    }
}
share|improve this answer
2  
This is brilliant! Wish I could've given you so many more upvotes! – SNag Jul 1 '15 at 1:19
    
The best solution. – Jerad Rose Sep 22 '15 at 14:05
    
@PaulZahra: This is mine one which I use. I don't need to cut-down your solution in order to post or repost it again. Please remove down-vote right now. – Priyank Sheth Jan 25 at 10:42
1  
@SimpleMan I am not claiming copyright over a solution... I didn't mean to imply you did a copy and paste exercise... the point I was trying to make is that it is in fact a duplicate answer of what I posted 14 mins earlier... and as such I downvoted it... isn't that fair? – Paul Zahra Jan 25 at 10:59
    
@PaulZahra I don't think so its duplicate. So many folks post same anser in matter of few minutes or hours. So does that mean that they deserve down-vote? Do you think that is good for anyone? Have you compared our answers line by line? Where did you found duplication? Please justify it properly. – Priyank Sheth Jan 27 at 3:46

in the view

<form action="/Controller_name/action" method="Post>

 <input type="submit" name="btn1" value="Ok" />
 <input type="submit" name="btn1" value="cancel" />
 <input type="submit" name="btn1" value="Save" />
</form>

in the action

string str =Request.Params["btn1"];
if(str=="ok"){


}
if(str=="cancel"){


}
if(str=="save"){


}
share|improve this answer

You can use JS + Ajax. For example, if you have any button you can say it what it must do on click event. Here the code:

 <input id="btnFilterData" type="button" value="myBtn">

Here your button in html: in the script section, you need to use this code (This section should be at the end of the document):

<script type="text/javascript">
$('#btnFilterData').click(function () {
    myFunc();
});
</script>

And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):

function myFunc() {
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "/myController/myFuncOnController",
        data: {
             //params, which you can pass to yu func
        },
        success: function(result) {

        error: function (errorData) {

        }
    });
};
share|improve this answer
    
Another great answer which keeps roles separated. No one should need to touch the controllers for this kind of UI change. – Charles Roberto Canato Dec 21 '15 at 17:13

The cleanest solution I've found is as follows:

This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.

In your view:

@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
    if (isOnDli)
    {
        <button name="removeDli" value="@result.WeNo">Remove From DLI</button>
    }
    else
    {
        <button name="performDli" value="@result.WeNo">Perform DLI</button>
    }
}

Then in your action:

    public ActionResult DliAction(string removeDli, string performDli)
    {
        if (string.IsNullOrEmpty(performDli))
        {
            ...
        }
        else if (string.IsNullOrEmpty(removeDli))
        {
            ...
        }

        return View();
    }

This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:

In your view:

@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{

        <button name="weNo" value="@result.WeNo">Process This WeNo</button>

        <button name="weNo" value="@result.WeNo">Process A Different WeNo This Item</button>
}

Then in your action:

    public ActionResult DliAction(string weNo)
    {
        // Process the weNo...

        return View();
    }
share|improve this answer

You could use normal buttons(non submit). Use javascript to rewrite (at an 'onclick' event) the form's 'action' attribute to something you want and then submit it. Generate the button using a custom helper(create a file "Helper.cshtml" inside the App_Code folder, at the root of your project) .

@helper SubmitButton(string text, string controller,string action)
{   
    var uh = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);
    string url = @uh.Action(action, controller, null);   
    <input type=button  onclick="(
                                       function(e)
                                                 {
                                                   $(e).parent().attr('action', '@url'); //rewrite action url
                                                   //create a submit button to be clicked and removed, so that onsubmit is triggered
                                                   var form = document.getElementById($(e).parent().attr('id'));
                                                   var button = form.ownerDocument.createElement('input');
                                                   button.style.display = 'none';
                                                   button.type = 'submit';
                                                   form.appendChild(button).click(); 
                                                   form.removeChild(button);              
                                                  }
                                      )(this)" value="@text"/>
}

And then use it as:

@Helpers.SubmitButton("Text for 1st button","ControllerForButton1","ActionForButton1")
@Helpers.SubmitButton("Text for 2nd button","ControllerForButton2","ActionForButton2")
...

Inside your form.

share|improve this answer
    
While the chosen answer and most of the other ones are functional, I'd rather choose this answer 'cause it beautifully keeps roles separated. Controllers shouldn't be modified for this kind of UI changes (provided you already have the controller logic ready). As such, using javascript keeps the changes where they belong: UI only. – Charles Roberto Canato Dec 21 '15 at 17:12

Try wrapping each button in it's own form in your view.

  @using (Html.BeginForm("Action1", "Controller"))
  {
    <input type="submit" value="Button 1" />
  }

  @using (Html.BeginForm("Action2", "Controller"))
  {
    <input type="submit" value="Button 2" />
  }
share|improve this answer
1  
What if i need the form values for both buttons but I take different actions like edit or delete – Chad Aug 15 '14 at 16:40

This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".

@{
  if (IsPost)
    {
       if(Request["btn"].Equals("button_A"))
        {
          Response.Redirect("PageA.cshtml");
        }
      if(Request[&quot;btn"].Equals("button_B"))
        {
          Response.Redirect(&quot;PageB.cshtml&quot;);
        }
  }
}
<form method="post">
   <input type="submit" value="button_A" name="btn"/>;
   <input type="submit" value="button_B" name="btn"/>;          
</form>

share|improve this answer
1  
mvc doesn't have postback, this is misleading. – RandomUs1r Sep 10 '14 at 22:30
    
@RandomUs1r this seems Razor standalone syntax (in fact, the property IsPost exists, but is not documented) – T-moty May 29 '15 at 9:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.