Send form parameter to the controller via ajax

0

I have an Index with a form, I need to fill out this form and when I click the Filter button, call the controller using ajax.

Index.cshtml

 @using (Html.BeginForm("ResultadoPesquisa", "RelatorioDesempenhoData", FormMethod.Post))
 {
     @Html.DisplayName("Item de Contrato")
     @Html.DropDownList("ItemContratoId", String.Empty)
     @Html.DisplayName("Mes")
     @Html.DropDownList("MesId", String.Empty)
     @Html.DisplayName("Ano")
     @Html.DropDownList("AnoId", String.Empty)
     @Html.DisplayName("Ativo")
     @Html.DropDownList("Ativo", new SelectList(new List<string> { "Ativo", "Inativo" }, String.Empty), String.Empty)

     <input type="submit" value="Filtrar" onclick="exibeBarChart(ItemContratoId, IndicadorId, MesId, AnoId, Ativo)"/>
 }

Controller.cs

public string ResultadoPesquisa(int? ItemContratoId, int? IndicadorId, int? MesId, int? AnoId, string Ativo, string Limpar)
{
    var avaliacaoDesempenho = ad.BuscaFiltrada(ItemContratoId, IndicadorId, MesId, AnoId, Ativo).ToList());

    //...

    var json = JsonConvert.SerializeObject(obj);

    return json;
}

JavaScript.js

var json;
function exibeBarChart(ItemContratoId, IndicadorId, MesId, AnoId, Ativo) {

    $.ajax({
        url: '/RelatorioDesempenhoData/ResultadoPesquisa',
        type: 'POST',
        data: { ItemContratoId: ItemContratoId, IndicadorId: IndicadorId, MesId: MesId, AnoId: AnoId, Ativo: Ativo },

        success: function (data) {
            json = data;
            var dado = JSON.parse(json);
            //...
        },
        error: function (data) {
            json = "error";
        }
    });
}

It turns out that the controller is being called, but not by Ajax. And at the end of the controller execution, I'm redirected to a page with json

Any suggestions or possible solutions?

Thankful

    
asked by anonymous 03.03.2017 / 19:05

1 answer

1

Hello, start by changing the type of input that triggers the event, try this:

First create the following javascript function:

function onClickBotaoFiltrar() {
   var ItemContratoId = $("select[id$='ItemContratoId'] option:selected").val();
   // não encontrei um correspondente do indicador id então vou simplesmente informar 0
   var IndicadorId = 0;
   var MesId = $("select[id$='MesId '] option:selected").val();
   var AnoId = $("select[id$='AnoId'] option:selected").val();
   var Ativo = $("select[id$='Ativo'] option:selected").val();

   exibeBarChart(ItemContratoId, IndicadorId, MesId, AnoId, Ativo)
}

After this change the button to

<input type="button" value="Filtrar" onclick="onClickBotaoFiltrar()"/>

I hope this can help.

    
03.03.2017 / 19:10