I try to send a JSON object back to the server. This is my AJAX call:
$.ajax({
url: '/Home/NewService',
async: false,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCES");
}
});
The evaluation of JSON.stringify(props) in the browser's debugger is
"[{"name":"firstName","value":"firstValue"}]"
This is the method in the controller which is being called:
[HttpPost]
public void NewService(dynamic json)
{
Response.Write(json);
}
The problem I have is that always the json variable from above is an empty object.
The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong.
Thank you.
I don't think you can bind to a dynamic type the way you're trying to. You can try to create a class that maps your data, something like:
public class Content
{
public string Name { get; set; }
public string Value { get; set; }
}
Now in your action:
[HttpPost]
public ActionResult NewService(Content[] data)
{
// sweet !
}
And in your js like Olaf Dietsche said you need to specify your contentType:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/Home/NewService',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
According to jQuery.ajax(), the default content type is is application/x-www-form-urlencoded. If you want to send the data as JSON, you must change this to
$.ajax({
url: '/Home/NewService',
contentType: 'application/json',
...
});
Use the following code to solve this problem
Ajax Call
function SaveDate() {
var obj = {};
obj.ID = '10';
obj.Name = 'Shafiullah';
$.ajax({
url: '/Home/GetData',
dataType: "json",
type: "Post",
contentType: 'application/json',
data: JSON.stringify({ ID: obj.ID, Name: obj.Name }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data.id + ' , ' + data.name);
},
error: function (xhr) {
alert('error');
}
});
}
My controller action method
[HttpPost]
public IActionResult GetData([FromBody] Employee employee)
{
return Json(employee);
}
Related
I have this ajax call below
$(function(){
$.ajax({
type: "GET",
url: '/CafeTableDetails/GetTotalItems',
data: '{"url":"test"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger
alert("some error");
}
});
});
and it can call the action method of my controller in C# MVC /CafeTableDetails/GetTotalItems
public ActionResult GetTotalItems()
{
bool isSuccess = true;
return Json(new { isUpdateSuccess = isSuccess, JsonRequestBehavior.AllowGet });
}
But as the action method return it back as Json, it falls into error. The XMLHttpRequest return state is 4, textStatus = "Error" and errorThrown is "Internal Server Error". How do I troubleshoot this further?
Your ajax method should be :
$.ajax({
type: "GET",
url: "/CafeTableDetails/GetTotalItems",
data: JSON.stringify({ url: 'test' }),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText);
}
});
and your controller action method will be:
[HttpGet]
public JsonResult GetTotalItems(string url)
{
// some business logic and return
return Json(url, JsonRequestBehavior.AllowGet);
}
i have c#.net web service like this
[WebMethod]
public string GetReportResult(int ReportID,params object[] Parameters)
{
return "hello";
}
[WebMethod]
public string Hello(string hello)
{
return hello;
}
for hello function i can call function but GetReportResult i cant
my jquery ajax is this
var webMethod = "ws.asmx/Hello";
var parameters = "{'ReportID':10,}";
$.ajax({
type: "POST",
url: "ws.asmx/GetReportResult",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: parameters,
success: function (msg) {
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
i want to call this web service by jquery but i don't know how to send data to params value
can everybody help me?
I sent the input using an array in jQuery. Here is a working sample of the code
$(document).ready(function() {
var cars = ["Saab", "Volvo", "BMW"];
var webMethod = "ws.asmx/Hello";
var parameters = "{'ReportID':10,'Parameters':['Name1','Name2']}";
$.ajax({
type: "POST",
url: "ws.asmx/GetReportResult",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: parameters,
success: function(msg) {
alert(msg.d);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
I have this at my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteUser(UserViewModel viewModel)
{
}
I have this at my cshtml:
<input type="button" id="btnDelete" value="Delete" />
I have this at my js file:
$('#btnDelete').click(function (e) {
});
How do I call controller function from js file?
$.post("Controller/CreateUser", dataToPost)
.done(function(response, status, jqxhr){
// this is the "success" callback
})
.fail(function(jqxhr, status, error){
// this is the ""error"" callback
});
or
var data = {
username: $('#username').val().trim(),
password: $('#password').val()
};
$.ajax({
type: "POST",
url: "Controller/CreateUser",
content: "application/json;",
dataType: "json",
data: JSON.stringify(data),
success: function(d) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
ps: compose the data object according to the UserViewModel properties.
Inside the button click, execute ajax request
$('#btnDelete').click(function (e) {
$.ajax({
type: "POST",
url: 'controller/DeleteUser',
dataType: "json",
success: function(data){
//html content
},
});
}
It's very easy to access any controller method using ajax post method.
As here I'm getting states as per selected country using
'RegionesController' method name 'GetStates' also here I'm passing
CountryId to get states as per this id.
EX:
function GetStates() {
$.ajax({
type: "POST",
async: false,
url: abp.appPath + 'Regiones/GetStates?CountryId=' + $("#ddlCountry").val(),
success: function (result) {
//return data or object
},
error: function (err) {
abp.notify.info(err.statusText);
}
});
}
I am trying to pass a single parameter (string value) to webapi controller but, it is not working. The parameter value is reaching the controller as 'null'. Here is my WebApi config,
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}"
);
}
}
Controller:
[HttpPost]
public HttpResponseMessage GetDataView(string request)
{
try
{
var result = DB.GetDataView(request);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
catch (Exception ex)
{
//todo: log exception
throw ex;
}
}
AJAX
var serverName = 'ds100';
$.ajax({
url: 'api/ServerInfo/GetDataView',
type: 'POST',
dataType: 'json',
data: serverName,
success: function (data, textStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
}
Am I missing anything? Any help is appreciated.
The issue seems to be on you ajax parameters the data parameter receives an object (json) that holds a property for each of the values you are passing in the request, I think you should use
var serverName = 'ds100';
$.ajax({
url: 'api/ServerInfo/GetDataView',
type: 'POST',
dataType: 'json',
data: {request: serverName} ,
success: function (data, textStatus, xhr) {
},
error: function (xhr, textStatus, errorThrown) {
}
and that should do it
I'm passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the client side but the matching parameters on the server side are null.
Here is the javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List/AddItem",
data: "{ ListID: '1', ItemName: 'test' }",
dataType: "json",
success: function(response) { alert("item added"); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Here is the controller method:
Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
'code removed for brevity
'ListID is nothing and ItemName is nothing upon arrival.
return nothing
End Function
What am I doing wrong?
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType and set data without double quotes.
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
In my case, if I remove the the contentType, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.