Submitting Ajax request from external javascript file in ASP.NET MVC - javascript

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?
Ajax call (From external JS file)
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Controller Action Method (That should be catching the request)
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public void AjaxEndpoint()
{
var thing = 1 + 2;
}
// AJAX endpoint for GetProducts.js
[HttpPost]
public void AjaxEndpoint(string jsonData)
{
var thing = 1 + 2;
}
}
Error I'm getting

You either need to remove the contentType option
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
dataType: "json",
success: successFunc,
error: errorFunc
});
or alternatively, stringify the data
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: JSON.stringify({ jsonData: "testing" }),// modify
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});

Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page
[HttpPost]
public ActionResult ajaxcall(string ids)
{
String Data = code to perform
return Json(Data);
}
this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

Related

Cannot send data from aspx file to code behind using $.ajax({ type: "POST", using VS2017 C#

I'm using web-forms to collect data from a form and then send the data to the code-behind to send to an API. Using a button I'm calling a JavaScript method which collates the data and then sends to my aspx.cs file to send to the API. The Html code for the button is
<button class="search btn" ID="btnSearch" onclick="searchApi(); return false;"><i class="fas fa-search"></i>Search</button>
This runs the searchAPI() function which works and creates a concatenated string called SearchData. The Javascript code looks like this
var searchString = JsonData;
var trimsearchString = searchString.replace(/,/g, '');
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
The method GetAPI in my Default.aspx.cs file is never called. The method code is
[System.Web.Services.WebMethod]
public static void GetApi(string searchData)
{...
The success: function (data) returns success but the code behind method is never called, can someone please tell me what I am missing.
fix the ajax data, it seems that method with this parameter can' t be found
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: { searchData: trimsearchString},
//or if it is still problem, you can even try
data: JSON.stringify( { searchData: trimsearchString}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
and your webmethod should return something
[WebMethod]
public static string GetApi(string searchData)
{
return searchData
}

How to httppost a list of objects?

I have this list of objects which I need to send from my angularjs javascript code:
var dataToSend = [{
SubId: "c9cb1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah"
}, {
SubId: "aaaa1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah2"
}]
I've tried these different variations but none of them are working:
1.
$http.post("url",
{
dataType: 'json',
headers: {
contentType: "application/json; charset=utf-8",
},
method: "POST",
data: dataToSend,
}).then...
2.
$http.post("url",
{
data: $.param(dataToSend),
}).then...
3
$http.post("url",
{
data: angular.toJson(dataToSend),
}).then...
4
$http.post("url",
{
data: { customers: dataToSend },
}).then...
5
$http.post("url",
{
data: JSON.stringify({ customers: dataToSend }),
}).then...
My API side code is (I have tried with [FromBody] attribute but no luck there):
[HttpPost]
public async Task<JsonResult> CreateCustomers(List<Customer> customers)
{
// customers is always null
}
And this is my Customer.cs:
public partial class Customer
{
public System.Guid SubId { get; set; }
public string CustomerName { get; set; }
}
Can you please help me? I have tried posting to CreateCustomers(Customer c) without using a list and its working as expected. But when I use a list, its always coming as null on the other side.
EDIT:
$.ajax is working but $http.post isn't. Any idea why?
var request = $.ajax({
dataType: "json",
url: "url",
method: "POST",
data: { '': dataToSend }});
Are you sending JSON ( Include dataType: 'json')
$http({
url: "url",
dataType: 'json',
method: 'POST',
data: dataToSend,
headers: {
contentType: "application/json; charset=utf-8",
}
})
In C# add FromBody in parameter
[HttpPost]
public async Task<JsonResult> CreateCustomers([FromBody]]List<Customer> customers)
{
// customers is always null
}
More on Ajax parameters
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc.
This should work. post full code if you face issue
use [ModelBinder] in front of your param.
[HttpPost]
public async Task<JsonResult> CreateCustomers([ModelBinder]List<Customer> customers)
{
// customers is always null
}
Web API only uses model binding for simple types, falling back on formatters for everything else. Adding [ModelBinder] forces the complex types to use model binding anyway.
Your post data is not matched with the parameter List<Customer>.
Change your server side method to something like:
[HttpPost]
public async Task<JsonResult> CreateCustomers(JObject queryParam)
{
// populate your list here
// for eaxample : var customers = queryParam["customers"].ToString();
}
And also you can use this code to send data to the server:
$http({
url: 'url',
dataType: 'json',
method: 'POST',
data: jsonData,
headers: { "Content-Type": "application/json" }
}).success(function(response){ $scope.response = response;
}).error(function(error){ $scope.error = error; });

Ajax Not Working With C# Controller Action With 2D Array Parameter

My Ajax is not hitting my controller action. What could be the reason?
My Controller Action
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
My Ajax
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": rosterArray, "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
If you are using type: 'Post' in AJAX, that means you need to add a Request type in Controller.
Try using this in controller,
[HttpPost]
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
Use httpPost in the Method for define type of response.
at client side
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": JSON.stringify(rosterArray), "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
and your controller code can be like this:
[HttpPost]
public ActionResult Save_Data(string rosterArray, int Pricelist_Id, int Group_Id)
{
string [][] convertedArray = JsonConvert.DeserializeObject<string [][]>(rosterArray);
}
Hope this works
Note: But you need to incude using Newtonsoft.Json;

How to call this.Page (server page) from javascript

I have methos to display content of page at server side like
DisplayDetails(Page PageNema)
{
///
}
How can i call this function from javascript as well as how can i pass Page argument from Javascript
If it's WebForm you must set this method as WebMethod, so then you can call this method from jQuery. Something like that:
Client Side.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Server side:
public partial class _Default : Page
{
[WebMethod]
public static string DisplayDetails()
{
//your code to retrieve details here
return Details;
}
}
[WebMethod]
public static string DisplayDetails(parameter1,parameter2,etc...)
{
return something;
}
Client side code
<script type="text/javascript">
function functionName(callback) {
$.ajax({
type: "POST",
url: 'PageName.aspx/DisplayDetails',// your function name
data: '{"argument1","argument2",etc...}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// If u want something from serverside function then write your code here
},
error: function (e) {
}
});
}
</script >

Dynatree ASP.NET MVC: post tree to server

I want to post data from dynatree to my asp.net mvc server via ajax. I use the model classes (Dynatree with ASP.NET MVC) from Steve which work well for getting data from the server to the client. But i have still problems with posting the tree data to the server.
Client:
var td = $("#tree").dynatree("getTree").toDict();
var json = JSON.stringify(td);
$.ajax({
type: "POST",
url: "/parttree",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
Server:
[POST("/parttree")]
public ActionResult TreeData2( List<TreeItem> ot)
{
// ot is always null here
}
Content of json in VS debugger:
{"title":null,"key":"_1","isFolder":false,"isLazy":true,"tooltip":null,"href":null,"icon":null,"addClass":null,"noLink":false,"activate":false,"focus":false,"expand":true,"select":false,"hideCheckbox":false,"unselectable":false,"children":[{"title":"root","key":"_2","isFolder":false,"isLazy":false,"tooltip":null,"href":null,"icon":null,"addClass":null,"noLink":false,"activate":false,"focus":false,"expand":false,"select":false,"hideCheckbox":false,"unselectable":false,"children":....
I would say that it would be the following :
$.ajax({
type: "POST",
url: "/parttree",
data: {tree: json},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
And your MVC Action would be :
[HttpPost]
public ActionResult PartTree(FormCollection form)
{
List<TreeItem> ot = new JavaScriptSerializer().Deserialize<List<TreeItem>>(form["tree"]);
}
Although you are probably looking to a JsonResult not an ActionResult if you are returning JSON.

Categories