I want to pass data between my view and my controller. I'm doing something wrong because it doesn't work.
JavaScript Front-end Code:
$.ajax({
url: '@Url.Action("GetOid","SearchPerson")',
data: {oid : 1},
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
// return values
console.log("Success!" + data.oid);
},
error: function () { console.log('error!!'); }
});
C# Controller Code:
int CustomerId=0;
[HttpPost]
public ActionResult GetOid(int Oid)
{
// some code here to assign the value to a global var.
CustomerId = Oid;
ViewBag.id = Oid;
return Json(new { oid = CustomerId });
}
});
Make this change to your ajax data property. It needs to be passed as string.
data: JSON.stringify({ "Oid": 1 }),
Also your controller parameters and data parameters are need to be same. The are case sensitive.
public ActionResult GetOid(int Oid)
Last as mentioned return it in json format.
return Json(new { oid = CustomerId });
Javascript doesn't know anything about variables you set on the server. You need to return json to client like so:
return Json(new { oid = CustomerId });
use
public JsonResult GetOid(int Oid)
to set the response headers properly
This baffled many newbies,
console.log("Success!" + **data.Data.oid**);
You should learn fire debugger on browser side and look at what concerns you on watch window.
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.