Receive data in MVC 5 controller

0

I have the following problem I am trying to send some data from ajax to my mvc driver but it did not manage to recover them this is my code:

   var Url = '@Url.Action("Save", "InspectionDailies")';
    var user = 0;
    function getval(sel) {
        user = sel.value;
    }

    $("#save").on("click", function () {

        var idinsp = $('#bookId').val();
        if (user == 0) {
            swal('¡Alert!', 'Select a User!.', 'error');
            return;
        }
        var ids = { "data": [{ "list": list, "user": user }] }
        $.post(Url, ids, function (data) {
            swal('Info', 'Success', 'success');
            $("#modalUser").trigger('click');
            location.reload();
        });
    });

and the controller is this:

public class InspectionDailiesController : Controller
{
 [HttpPost, ActionName("Save")]
    public async Task<ActionResult> Saved(string ids)
    {
        dynamic jsonObject = ids;
        var id = string.Empty;
        var user = string.Empty;

        var inspectionDaily = await db.InspectionDaily.FindAsync(id);
        if (inspectionDaily == null)
        {
            return HttpNotFound();
        }

        try
        {
            inspectionDaily.IDUser = int.Parse(id);
            inspectionDaily.Status = 2;
            inspectionDaily.IdInspectionStates = 2;
            db.Entry(inspectionDaily).State = EntityState.Modified;
            await db.SaveChangesAsync();
            TempData["msg"] = "<script>alert('Change succesfully');</script>";
        }
        catch (Exception)
        {

            throw;
        }
        ViewBag.Userdb = new SelectList(CombosHelper.GetUsersDB(), "IDUser", 
 "FirstName");
        ViewBag.IdInspectionStates = new SelectList(db.InspectionStates, 
"IdInspectionStates", "Description", inspectionDaily.IdInspectionStates);
        return RedirectToAction("Index");

    }
}

Thanks for your help.

    
asked by Javier Penagos 06.04.2018 в 01:13
source

1 answer

0

There are several ways to do this. I leave you here one:

In your JS you do something like this:

  var cadenaIds = list.join();
  var form = new FormData();
  form.append("listaIds", cadenaIds);
  form.append("user", user);
  $.post(....);

In your CS:

  public async Task<ActionResult> Saved(string listaIds, string user){
       string[] arregloIds = listaIds.Split(new char[] {','})
       //si los id son Int puede iterar sobre el arreglo y haces el parse Int por cada String

      //......
  }

Another option might be that in your JS you use Json.Stringify and in your CS you deserialize that Json.

I hope it serves you.

    
answered by 06.04.2018 / 20:55
source