Problem with jQuery post to ASP.NET Core controller - javascript

I have gone through this solution on stackoverflow but I couldn't solve my problem.
In HomeController I have a method named as Audit which I want to be posted from /Home/Index page's script through jQuery. The controller looks like:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody] JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}
In the /Home/Index pages's javascript file I have tried to post a JSON Object to that Audit in a way like this:
var auditData = {};
$(document).ready(function(){
var request = $.getJSON('http://www.geoplugin.net/json.gp', function (responseData, status) {
auditData = {
Latitude : responseData.geoplugin_latitude,
Longitude : responseData.geoplugin_longitude
};
$.post('Audit', auditData, function (response) {
console.log(response);
});
});
});
I want the auditData object to be posted as JObject in /Home/Audit but something is going wrong. I think there is problem either in controller or, in $.post method. How can I solve this problem?

Your post URL is wrong, and you need to name the data you're posting back as jObject as well to match what you defined in your controller.
$.post('#Url.Action("audit", "home", new { area = "" })', { jObject: auditData },
function (response) {
console.log(response);
});

There are multiple issues in your current code, check points below one by one:
As the suggestion from Rory, your request url is wrong, which should be Home/Audit
If you post request without antitoken, you should remove [ValidateAntiForgeryToken]
You should post request data with json instead of form data.
Code:
Client
#section Scripts{
<script type="text/javascript">
var auditData = {};
$(document).ready(function(){
auditData = {
Latitude : "l1",
Longitude : "l2"
};
$.ajax({
type: 'POST',
url: 'Home/Audit',
data: JSON.stringify(auditData),
success: function(data) { alert('data: ' + data); },
contentType: "application/json"
});
});
</script>
}
Server:
public class HomeController : Controller
{
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody]JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

Send javascript variables to spring controller

I'm trying to develop simple application using spring mvc and I need to pass javascript parameters to spring controller. I have tried several methods and none of them were worked. Following is my javascript and spring controller. Please help me to sort this issue.
Java script
function searchViaAjax(id) {
alert(id);
$.ajax({
type : "POST",
contentType : "application/json",
url : "search/api/getSearchResult",
data : JSON.stringify(id),
dataType : 'json',
timeout : 100000,
success : function(id) {
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
AjaxController.java
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult")
public String getSearchResultViaAjax(#RequestParam(value = "id") int id) {
System.out.println("come to ajax"+ id);
return "hello";
}
}
When you pass json as requestbody then above call is applicable. To send request param you have to as below:
Use following ajax call:
function searchViaAjax(id) {
var tempId = id;
$.ajax({
type : "POST",
url : "/search/api/getSearchResult",
data : {id:tempId},
timeout : 100000,
success : function(id) {
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
also you can acheive this using get method as below:
function searchViaAjax(id) {
$.ajax({
type : "GET",
url : "/search/api/getSearchResult/"+id,
timeout : 100000,
success : function(id) {
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
#Controller
public class AjaxController {
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult/{id}")
public String getSearchResultViaAjax(#PathVariable(value = "id") Integer id)
{
return String.valueOf(id);
}
}
When you use JSON.stringify, you are actually sending a JSON object to your spring controller's method. All you have to do is wrap your json object as a java object like so.
public class UserId {
private int id;
// setters and getters
}
And in your controller's method use #RequestBody to map your JSON to your UserId class like so
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult", method = RequestMethod.POST)
public String getSearchResultViaAjax(#RequestBody UserId user) {
System.out.println("come to ajax" + user.getId());
return "hello";
}
PS: Haven't tested it but should work.
It is a post request you are making from your ajax to controller.
You are missing "methodType=RequestMethod.POST" on your spring controller.
Replace #RequestMapping(value = "/search/api/getSearchResult") with
#RequestMapping(value = "/search/api/getSearchResult", methodType=RequestMethod.POST)

how to get value from document.getelementbyid in c sharp

I want to pass the element's value into a controller
JavaScript:
var element = document.getElementById("valueSelected");
Query String
Document.location="/ControllerName/ActionName/Value";
Ajax
$.Post('/ControllerName/ActionName/',{Parameter: element});
No problem
Script
function Delete() {
$.getJSON("/ControllerName/ActionName/", {Id : Value}, function (data)
{
alert(data)
})
};
C#
public JsonResult ActionName(int? id)
{
string Data = "Sample Data";
return Json(Data, JsonRequestBehavior.AllowGet);
}
Let suppose Home is your Controller.
Add a function in your controller who can handle your ajax request. Suppose function name is getValue:
public void GetValue(string elementValue)
{
//add your controller logic here
}
In your javascript, I use jquery to perform ajax request, you need to jquery to do this so:
var element = document.getElementById("valueSelected");
$.ajax({
type: "POST",
data : { elementValue : $(element).val() },
url: '#Url.Action("GetValue", "Home")'
}).done(function (data) {
console.log('done');
});

Calling controller with ajax in mvc

I'm trying to fetch data from a controller and update my view using ajax.
This is my controller:
public class PatientController
{
DatabaseContext db = new DatabaseContext();
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.FirstOrDefault(p => p.Cpr == "2410911615");
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And this is my ajax call:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
dataType: 'json',
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
When i call the function i always get the error alert.
GET http://localhost:51140/Patient/GetPatientFromCpr 404 (Not Found)
Can someone point out what's wrong?
(EDIT)
I now get a new error after adding ": Controller"
GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Your 'PatientController' is not a Controller (it does not inherit from Controller)
public class PatientController : Controller
{
....
}
Inherit you PatientController with Base Controller Class
public class PatientController : Controller
In controller
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.where(p => p.Cpr == "2410911615").FirstOrDefault();
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And Specify the type of ajax calling
type: "POST" or type: "GET" ....
This will help you to fix error
Try using this, may be this works..!!
View:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
//dataType: 'json',
type:"POST", // GET or POST
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
Controller:
public class PatientController : Controller
{
....
}

Problems updating database with Jquery.Ajax

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}
I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

Categories

Resources