Send view to controller values by jquery

1

I'm doing an application in .Net C #, and I wanted to make an input and a button that would send the information to my controller by jquery/ajax , and I have no idea how to accomplish this, I need to pass the information by ajax to controller .

My controller calls BarCodeController and and route and BarCode / BarGenerate

Below is my controller

public ActionResult BarGenerate(string Barconteudo)
{
    var BarObj = new QRCodeModel();
        BarObj.barconteudo = Barconteudo;

    return View(BarObj);
}
    
asked by anonymous 21.05.2018 / 21:17

1 answer

1

You can do this as follows

View:

<form id="myForm">
    <input type="text" name="Barconteudo" id="Barconteudo" />
    <input type="text" name="Teste" id="Teste" />
    <input type="button" btn="myBtn" value="Enviar" onclick="enviaInformacoes()" />
</form>
<script>
    function enviaInformacoes() {
        var objeto = $("#myForm").serialize();
        $.ajax({
            url: "/BarCode/BarGenerate",
            type: "POST",
            data: objeto,
            datatype: "json",
            success: function (data) {
                alert(data.Mensagem);
            }
        });
    }
</script>

Controller:

public ActionResult BarGenerate(QRCodeModel model)
{
    return Json(new { Mensagem = $"{model.Barconteudo} - {model.Teste}" });
}

Model:

public class QRCodeModel 
{
    public string Barconteudo { get; set; }
    public string Teste { get; set; }
}

Explanation:

We have two inputs one with name and ID Barconteudo other Test and a button that when clicked calls the function enviaInformacoes() .

In the function, with JQuery a serialize of form is made that causes all fields to be "played" in an object (it will create an object with the Barconteudo and Test fields), after that, with % with% is indicated with $.ajax , type (Post or Get), data to be sent, type (json) and if successful in the request, an alert is issued with the field "Message".

No URL has been changed to receive an object of type QRCodeModel containing the Barconteudo and Test properties. in addition to the return type that was changed to controller with the "Message" field

    
21.05.2018 / 21:35