简体   繁体   中英

How do I pass a parameter to an mvc ActionResult using Jquery Ajax?

I am trying to pass an id parameter back to MVC action result using Jquery Ajax. I want to execute a StoredProcedure which is expecting the id as a parameter.

I have tried various methods to pass the id back to the ActionResult but I keep failing and getting different errors.

Can somebody please assist and show me what I'm doing wrong.

function UpdateUsingId(Id) {
  $('table').on('click', 'tr', function() {
    var Id = $(this).find('td').first().text().trim();
    $.ajax({
      url: '@Url.Action("CreateNewRecord", "Sales")',
      data: Id,
      success: function(data) {
        alert("succes");
      },
      error: function(error) {
        alert(JSON.stringify(error));
        cache: true;
      }
    })
  })
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateNewRecord(int? Id) 
{
  var data = db.SP_GetIdForUpdate_Insert(Id);
  return View(data);
}

You should pass a parameter by this way

  function UpdateUsingId(Id) {
  $('table').on('click', 'tr', function() {
    var Id = $(this).find('td').first().text().trim();
    $.ajax({
      type: "POST",
      url: '@Url.Action("SaveData", "Sales")',
      data: {"Id":Id},
      success: function(data) {
        alert("succes");
      },
      error: function(error) {
        alert(JSON.stringify(error));
        cache: true;
      }
    })
  })
}

You have to pass data in Json format like this : {"Id":Id} and pass it in a save data action in sales controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM