38

I have a form in ASP.Net and razor.

I need to have two ways of submitting said form: one that goes through the Edit action, and another that goes through the Validate action.

How should I go about doing this?

I don't mind using JavaScript for this.

EDIT:

Using the custom attribute I get this error.

The current request for action 'Resultados' on controller type 'InspecoesController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Validar(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController System.Web.Mvc.ActionResult Resultados(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController

1

7 Answers 7

76

That's what we have in our applications:
Attribute

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}

Actions decorated with it:


[HttpParamAction]
public ActionResult Save(MyModel model)
{
    // ...
}

[HttpParamAction]
public ActionResult Publish(MyModel model)
{
    // ...
}

HTML/Razor

@using (@Html.BeginForm())
{
    <!-- form content here -->
    <input type="submit" name="Save" value="Save" />
    <input type="submit" name="Publish" value="Publish" />
}

name attribute of submit button should match action/method name

This way you do not have to hard-code urls in javascript

Sign up to request clarification or add additional context in comments.

13 Comments

Do you have an action attribute value set for your form? @using (Html.BeginForm()) should be enough. It's strange because at the moment of writing this comment I'm implementing exactly the same thing and it just works
Good. I've renamed mine as ButtonNameActionAttribute: then the controller looks a little cleaner and a touch more obvious.
this is easy in a pinch, but it causes a lot of other problems when you have other action methods in the same controller. Not to mention an implicit contract between the view and the controller (a big no-no). I've opted for a lightweight JS function that changes the form action before submitting, like @ŁukaszW.pl below
I like this approach. And if you would like to add HTML attributes , e.g. for Bootstrap, while keeping the default behavior of the parameterless Html.BeginForm() you can pass null for action and controller. Here is an example: Html.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal", role = "form" })
@Ramunas as people told you above, great solution! Not that it works, but it is also a clever approach and I like it a lot. Can't believe you received a -1, it happens to me as well every know and then - probably there are some hatters on SO. Vote up from me! :-)
|
43

You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:

<form id="myForm">
    <%-- form data inputs here ---%>
    <button id="edit">Edit</button>
    <button id="validate">Validate</button>
</form>

you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):

<script type="text/javascript">
      $("#edit").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Edit","MyController")");
          form.submit();
      });

      $("#validate").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Validate","MyController")");
          form.submit();
      });
</script>

6 Comments

I didn't knew about form.attr(). This should do the trick. Thanks.
With javascript/jquery you can manipulate any dom property, especially element attributes with attr(). If you're not sure if there is a method you need use jquery documentation (docs.jquery.com) - there's a lot of knowledge..
You should use the #edit syntax rather than button#edit, assuming you don't have duplicate IDs across different element types (about the only reason I could see that being used). Querying by ID is much faster. If you were using non-ID selector on the RHS, you'd be a little better off because it's paring the list down. But because the plain ID selector uses DOM.getElementById('') (at least, without having to first find all button elements), it will be faster.
@JoeBrockhaus - thats not related to this problem, but it's a good point so I've corrected my answer.
agreed, unrelated :) glad I could help!
|
8

If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. 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["btn"].Equals("button_B"))
        {
          Response.Redirect("PageB.cshtml");
        }
  }
}
<form method="post">
   <input type="submit" value="button_A" name="btn"/>;
   <input type="submit" value="button_B" name="btn"/>;          
</form>

Comments

5

Here is a good eplanation: ASP.NET MVC – Multiple buttons in the same form

In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute (which I personaly prefer and suggest).

2 Comments

My answer is adopted version of the article :)
Perfect! Nice quick and easy implementation to use rather than clutter code in the view with JQuery/Javascript BTW, for custom ActionMethodSelectorAttribute approach where do you put this class? Does it need to be registered to the framework some how?
4

With HTML5 you can use button[formaction]:

<form action="Edit">
  <button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
  <button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->
</form>

Comments

3

<input type="submit" value="Create" name="button"/>
<input type="submit" value="Reset" name="button" />

write the following code in Controler.

[HttpPost]
        public ActionResult Login(string button)
        {
            switch (button)
            {
                case "Create":
                    return RedirectToAction("Deshboard", "Home");
                    break;
                case "Reset":
                    return RedirectToAction("Login", "Home");
                    break;
            }

            return View();
        }

Comments

1

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.