How to pass two parameters to a controller via ajax

1

I'm working on an ASP Mvc project, I have the following controller:

[HttpPost]
public ActionResult Asociar(int? id, int proveedorId)
{

    return PartialView("Companies");
}

In my view I pass these parameters in the following way:

<a class='asociar' style='color: #004881' href='/administrador/asociar/@item.CompañiaId' id='@item.CompañiaId' title='Asociar al Proveedor'>

This is my Ajax.

    $('.asociar').click(function () {
    var proveedorId = $("#proveedorId");
    $.ajax({
        url: this.href,
        type: "post",
        data: proveedorId,
        success: function (result) {
            if (result.success) {
                //Refresh
                window.location.reload();
            }
        }
    });
});

supplierId is a hidden item.

Currently both values are coming to the Controller, but I would like to know if it is the best way to do this, or if I am making an error.

    
asked by jose luis garcia 01.05.2016 в 06:09
source

2 answers

3

By invoking the controller action you can use json to send data

$('.asociar').click(function () {

    var params = {
        id: ..., //aqui defines el valor del parametro
        proveedorId: $("#proveedorId").val()
    };

    $.ajax({
        url: this.href,
        type: "post",
        data: params,
        success: function (result) {
            if (result.success) {
                //Refresh
                window.location.reload();
            }
        }
    });
});

Actually model binding of asp.net mvc is taking the id because you define it as part of the route when in the secure code you have something like this:

routes.MapRoute(
    "Default",                                              
    "{controller}/{action}/{id}",                           
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
);

When you use "{controller}/{action}/{id}" in the last parameter, it is optionally the id that you receive in the action.

But it would be nice if you can send it in a unified and controlled way using json.

    
answered by 02.05.2016 / 05:34
source
3

uses an object of js:

$('.asociar').click(function () {
    var proveedorId = $("#proveedorId");
    $.ajax({
        url: this.href,
        type: "post",
        data: { id: algunaId, proveedorId : provId } ,
        success: function (result) {
            if (result.success) {
                //Refresh
                window.location.reload();
            }
        }
    });
    
answered by 02.05.2016 в 05:33