Post JavaScript array with AJAX to asp.net MVC controller

前端 未结 6 2183
长情又很酷
长情又很酷 2020-12-01 12:23

My controller:

[HttpPost]
public ActionResult AddUsers(int projectId, int[] useraccountIds)
{
    ...
}

I\'d like to post the parameters to

6条回答
  •  失恋的感觉
    2020-12-01 13:12

    Using $.Ajax(), you can easily get the data from javascript to the Controller in MVC.

    As like,

    var uname = 'John Doe';
    
    $.ajax({
    
            url: "/Main/getRequestID",  // This is path of your Controller with Action Result.
            dataType: "json",           // Data Type for sending the data
    
            data: {                     // Data that will be passed to Controller
                'my_name': uname,     // assign data like key-value pair       
                 // 'my_name'  like fields in quote is same with parameter in action Result
            },
    
            type: "POST",               // Type of Request
            contentType: "application/json; charset=utf-8", //Optional to specify Content Type.
    
            success: function (data) { // This function is executed when this request is succeed.
                    alert(data);
            },
    
            error: function (data) {
                    alert("Error");   // This function is executed when error occurred.
            }
    )};
    

    then, on the Controller side,

    public ActionResult getRequestID(String my_name)
    {
    
        MYDBModel myTable = new Models.MYDBModel();
        myTable.FBUserName = my_name;
        db.MYDBModel.Add(myTable);
        db.SaveChanges();              // db object of our DbContext.cs
        //return RedirectToAction(“Index”);   // After that you can redirect to some pages…
        return Json(true, JsonRequestBehavior.AllowGet);    // Or you can get that data back after inserting into database.. This json displays all the details to our view as well.
    }
    

    Reference. Send Data from Java Script to Controller in MVC

提交回复
热议问题