Action call as parameter in Html.BeginForm - ASP .NET MVC 5

0

I have a code that queries a WebApi, writes to the database, and queries the database, in this application, a view that has 3 buttons, namely:

  • Query Ws
  • Insert BD
  • BD Query

I'm using @ Html.BeginForm to submit the button action and call ActionResult responsible for each render.

In the passage of parameters, only one action is allowed (obviously). How do I make it to have a "decision-making" or an "if", so that it calls the correct action by clicking its button?

Would it be better to use another type of form? Or any other ways for this?

In the code below the "QueryWs" is the parameterized action that "should change" when clicking a button other than "btnCsWs".

    @using (@Html.BeginForm("ConsultaWs", "Home", FormMethod.Get))
    {
            <text>codigo do país</text>
            @Html.TextBoxFor(model => model.RestResponse.result.country)
            <text>codigo do estado</text>
            @Html.TextBoxFor(model => model.RestResponse.result.abbr)
          <button type="submit" name="btnCsWs">Consulta WS</button>
          <button type="submit" name="btnInsereDB">Insere DB</button>
          <button type="submit" name="btnCsDB">Consulta DB</button>
    } 
    
asked by anonymous 23.02.2018 / 18:43

1 answer

1

In browsers that support HTML5, you can use the formaction attribute to submit button:

@using (@Html.BeginForm("ConsultaWs", "Home", FormMethod.Get))
{
        <text>codigo do país</text>
        @Html.TextBoxFor(model => model.RestResponse.result.country)
        <text>codigo do estado</text>
        @Html.TextBoxFor(model => model.RestResponse.result.abbr)
      <button type="submit" formaction="@Url.Action("CsWs", "Home")" name="btnCsWs">Consulta WS</button>
      <button type="submit" formaction="@Url.Action("InsereDB", "Home")" name="btnInsereDB">Insere DB</button>
      <button type="submit" formaction="@Url.Action("CsDB", "Home")" name="btnCsDB">Consulta DB</button>
}

This will cause submitting to submit on form, the request goes to formaction of the clicked button.

In browsers that do not support HTML5, you can add an event listener by clicking a button of type submit (you can improve the selector by delegating from a specific form, for example):

$(document).on('click', 'button[type="submit"]', function (event) {
  var action = $(this).attr('formaction');
  $(this).closest('form').attr('action', action);
});

JavaScript will increase support for non-html5 browsers, but if any user has javascript disabled and the browser is HTML5, the first option will allow it to work the way you need it.

Then it's okay to use both options at the same time:)

    
23.02.2018 / 19:02