$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data)
}
});
});
I am using the ajax call above to get a model back how would i use the model object in the success function. As in I need to be able to use the data like a views model like #model.Type lets say. how could i do that with the json data in the success?
The data object contains the properties passed down via the server.
You can then access them like:
var name = data.Name;
var testData = data.TestData;
Your Action could look like:
public JsonResult LeadCounts()
{
return Json(new { name = "Darren", testData = "Testing" });
}
In MVC3 you could do it like this:
public ActionResult LeadCounts()
{
var data = new { Count = 1, Something = "Something" };
return Json(data, JsonRequestBehavior.AllowGet);
}
In view:
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data.Count);
}
});
});
Related
using the following script, I am trying to access the variables being sent using data in the ajax function but I couldn't.
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '#Url.Action("UpdateOrder")', // to get the right path to controller from TableRoutes of Asp.Net MVC
dataType: "json", //to work with json format
type: "POST", //to do a post request
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false, //avoid caching results
data: { test: $(this).text() }, // here you can pass arguments to your request if you need
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
here is the action in the controller
public ActionResult UpdateOrder()
{
// some code
var test = Request.Form["test"];
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
I tried Request.Form["test"] but the value of it is null. how should I receive the objects of data?
Your ActionResult is GET And you have no input parameter for your ActionResult so either change those or see below:
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: /ControllerName/ActionName
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { test: comments },
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
Then within your controller:
public ActionResult UpdateOrder(string test)
{
// some code
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
Update
Remember if you want to use POST then action you are calling has to be [HttpPost] like:
[HttpPost]
public ActionResult Example()
When there is no HTTP above your ActionResult Then Its By Default Get.
The action method should be decorated with the [HttpPost] attribute. Have you used the debugger to ensure that you're actually calling in to that method?
You can always just define a view model in C# and then accept that as a parameter to your post method - Asp.MVC will parse the post data for you as long as the names of the values are the same as your model.
Have you marked your action method with [HttpPost] attribute. ?
This post helped me a lot. I did the GET but POST raise an Internal Server Error just with [HttpPost]:
[HttpPost]
public ActionResult SaveOrder(int id, string test, string test2)
So i had to set params data with JSON.stringify and it worked. My full ajax request for POST:
$.ajax({
url: "/Home/SaveOrder",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: JSON.stringify({ id:2, test: "test3", test2: "msj3" }),
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
I am trying to use Datatables within my webforms application.
unfortunatly I get the whole html page instead of json data :'(
this is my code.
<script type="text/javascript">
$(document).ready(function () {
$('#grid').dataTable({
"dataType": 'JSON',
"bServerSide": true,
"sAjaxSource": 'GategoriesManagement.aspx/GetPersonList',
"bProcessing": true,
"aoColumns": [
{ "sName": "d.name" },
]
});
});
</script>
my webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetPersonList()
{
List<personne> personeList = new List<personne>();
personne person = new personne();
person.name = "test1";
personeList.Add(person);
person = new personne();
person.name = "test2";
person = new personne();
person.name = "test3";
personeList.Add(person);
FormatedList list = new FormatedList();
list.iTotalDisplayRecords = 10;
list.iTotalRecords = 200;
list.aaData = personeList;
var javaScriptSerializer = new JavaScriptSerializer();
string jsonString = javaScriptSerializer.Serialize(list);
return jsonString;
}
and this is the alert that I get in the browser
DataTables warning: table id={id} - Ajax error
it appear that my webmethod is not accessible
what should I do ???
The magic piece of code which makes this work as of 1.10.12 is the ajax parameter. ASP.NET wraps JSON results in the .d property, so you need to execute the callback on that object.
$('#tableId').dataTable(
{
"processing": true,
"serverSide": true,
"stateSave": false,
"lengthMenu": [[10, 30, 100, -1], [10, 30, 100, "All"]], // 1st = page length values, 2nd = displayed options
ajax: function (data, callback, settings) {
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'POST',
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
$spinner.hide();
callback(data.d); // execute the callback function on the wrapped data
}
});
},
I really liked #Echilon answer, but I'd like to add that it's possible to send the Ajax request as GET too.
Having said that, and although OP's example didn't include a parameter in the GetPersonList() method, I'd like to show how parameters would need to be sent on an Ajax request depending if it's a GET or POST** request:
POST request
It doesn't matter if the value is of type int, string, boolean or an object, the way to send data is the same that #Echilon showed. Although here's a little variation:
data: function (data) {
data.parameterName = value;
return JSON.stringify(data);
}
And here's a brief example. Let's suppose that this is your original method:
[WebMethod]
//The parameter could be a int, string or bool
public static string GetPersonList(int|string|bool value)
{
//do something here...
}
And in your Ajax call:
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'POST',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.value = 10|"Test"|false; //Send the appropriate data according to the parameter type in your method
return JSON.stringify(data);
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
In case you need to send an object here's a brief example. Let's suppose that this is your original method:
class Person
{
public int Id { get; set; }
public string UserName { get; set; }
}
[WebMethod]
public static string GetPersonList(Person person)
{
//do something here...
}
Then in your Ajax call:
var $person = {};
$person.Id = 9;
$person.UserName = "jsmith";
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'POST',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.person = $person;
return JSON.stringify(data);
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
GET request
If you prefer to use a GET request, then the way to send the data varies a little. If the value is of type int or boolean, you can send it like this:
data: function (data) {
data.parameterName = value;
return data;
}
But if you want to send a string or an object, then you can send it like this:
data: function (data) {
data.parameterName = JSON.stringify(value);
return data;
}
Let's see a brief example. Let's suppose that this is your original method:
[WebMethod]
[ScriptMethod(UseHttpGet = true)] // I didn't include the ResponseFormat parameter because its default value is json
//The parameter could be a int or bool
public static string GetPersonList(int|bool value)
{
//do something here...
}
And in your Ajax call:
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'GET',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.value = 10|false; //Send the appropriate data according to the parameter type in your method
return data;
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
In case you need to send a string or an object here's a brief example. Let's suppose that this is your original method:
class Person
{
public int Id { get; set; }
public string UserName { get; set; }
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)] // I didn't include the ResponseFormat parameter because its default value is json
//The parameter could be an object or a string
public static string GetPersonList(Person person) // or (string value)
{
//do something here...
}
Then in your Ajax call:
var $person = {};
$person.Id = 9;
$person.UserName = "jsmith";
$('#tableId').dataTable(
{
//your DataTable options here
$.ajax({
url: "/UserService.asmx/GetUsers",
type: 'GET',
contentType: 'application/json; charset=utf-8',
//dataType: "json", only include this if you're expecting the result in json format
data: function (data) {
data.person = JSON.stringify($country);
//data.value = JSON.stringify("Test"); Or this one, depending the parameter of your method
return data;
},
dataSrc: "d.data" //DON'T forget to include this or your table won't load the data
},
// your columns settings here
});
I am trying to pass the data of the view model to one js method and from there I need to pass the VM to another controller method to show the data.
here is what I have did:
$(document).ready(function () {
var content = GetHomeContent('/Home/CastContent');
if (content) {
saveBDContent('/Message/Details/', content);
}
});
function GetHomeContent(url) {
var modelData;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
contentType: 'application/json',
success: function (data) {
if (data) {
modelData = data;
}
},
error: function (data) {
status = false;
}
})
return modelData;
};
function saveBDContent(url, data) {
var status = false;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
if (data == "200") {
status = true;
}
},
error: function (data) {
status = false;
}
})
return status;
};
The problem am facing is , the content I retrived from the method show the namespace of the ViewModel. When I pass that to the new controlled the Viewmodel content is coming null.
Do I need to add anything to get/Pass the proper content ?
The Dummy method skeleton
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM);
}
I have missed out the JsonRequestBehavior.AllowGet in my controller method, I have added and the results are coming perfectly.
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM,JsonRequestBehavior.AllowGet);
}
and also I have set the HTTP status as post in the jquery method
Do something like that in the Controller:
public JsonResult QuickSave(BookEntry bookEntry) {
YourViewModel model = new YourViewModel();
return Json(model);
}
EDIT >> The associated Javascript code is :
$.ajax({
type: "POST",
url: 'The URL',
data: 'The JSON data',
dataType: "json",
success: function (theViewModel) {
// Do some JS stuff with your model
},
error: function (xhr, status, error) {
// Do some error stuff
}
});
I am trying to pass an array variable from ajax to controller,
but I am not getting the values in controller
below is my code
AJAX
function userDetailsClass() {
var userDetails = {};
userDetails.age = 12;
userDetails.Name = "Vignesh";
userDetails.lastName = "s";
debugger;
$.ajax({
url: "Home/userDetails",
data: JSON.stringify({
UserDetailsParam: userDetails
}),
responseType: "json",
success: successfn,
error: errorfn
});
function successfn(result) {
};
function errorfn(result) {
};
}
Controller
public ActionResult userDetails( string UserDetailsParam){
return View();
}
I also tried
public ActionResult userDetails( string[] UserDetailsParam){
return View();
}
Your code should be like this
$.ajax({
url: "Home/userDetails",
data: {
"UserDetailsParam":JSON.stringify(userDetails)//change this
},
responseType: "json",
success: successfn,
error: errorfn
});
Try with this
var userDetails = {"age":'12',"Name":'Vignesh',"lastName":'s'};
Model:
public class JsonRequest
{
public string Data { get; set; }
}
Action:
[HttpPost]
public ActionResult Index(JsonRequest data)
{
return new JsonResult()
{
Data = string.Format("Data: {0}", data.Data), // data.Data == null here
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
AJAX:
$.ajax({
type: 'POST',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
JsonRequest object has an instance in Index action but it's Data property was not mapped to the passed JSON. How can I achieve this?
You need to remove JSON.stringify() call, because jQuery do it itself. And according standarts it's better to write {"Data" : "Hello world"} ("Data" in quotes).
Well you are specifying data not Data when passing the object back up to the server. This may be the root of the problem. Also specify the contentType in your AJAX request.
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("Index", "Home")',
cache: false,
data: JSON.stringify({ Data: "Hello World!" }),
success: function(data) {
alert(data);
}
});
http://api.jquery.com/jQuery.ajax/