Send view to controller values by jquery

Asked

Viewed 799 times

1

I am making an application in . Net C#, and wanted to do an input and a button that sends the information to my controller for jquery/ajax, and I have no idea how to accomplish this, I need to pass the information by ajax for controller.

My controller calls Barcodecontroller and and the route and Barcode/Bargenerate

Follow me down my controller

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

    return View(BarObj);
}
  • What’s the name of your Controller or the route to your Action? If you are sending a data by ajax, it should not return a view as a result...

  • My controller calls Barcodcontroller and and the route and Barcode/Bargenerate

1 answer

1

You can do it this way

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 another Testing and a button that when clicked calls the function enviaInformacoes().

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

In the controller was changed to receive an object of type Qrcodemodel that contains the properties Barconteudo and Testing. in addition to the type of return that has been changed to Json with the field "Message"

  • and if I have more than 1 field, type Barobj.barconteudo = Barconteudo; e Barobj.teste = Test;

  • 1

    I will edit with multiple fields, but in this case you can either pass field by field as parameter or create an object

Browser other questions tagged

You are not signed in. Login or sign up in order to post.