I can't get data from AJAX post request in C# controller - javascript

I want to send data from javascript to c# controller using ajax, but when the Add method in my controller is called all its arguments are null
AJAX:
function addRequest(name, price, about){
$.ajax({
url: 'Services/Add',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: {
'name' : name ,
'price' : price,
'about' : about,
},
dataType: "json",
success: (insert) => {
if (insert) {
$('#result').fadeIn(200).html(insert).fadeOut(200, () => {
location.reload()
})
}
}
})
}
My controller:
[ApiController]
[Route("[controller]")]
public class ServicesController: Controller
{
[HttpPost]
[Route("Add")]
public async Task Add(string? name, string? price, string? about)
{
await Context.Services.AddAsync(new Service
{
Name = name,
Price = price,
About = about
});
await Context.SaveChangesAsync();
}
}

I think binding of this controller in not working, you are sending object by ajax but you are expecting three separte primitives
try:
[HttpPost]
[Route("Add")]
public async Task Add(Service service)
{
await Context.Services.AddAsync(service);
}
or try adding setup binding attributes

try this
[HttpPost]
[Route("Add")]
public async Task Add(Service model) {
//
}

Try using a service class to receive the JSON rather using distinct values.
Follow below links to learn more.
https://www.aspsnippets.com/Articles/Pass-Send-Model-object-in-jQuery-ajax-POST-request-to-Controller-method-in-ASPNet-MVC.aspx
https://www.c-sharpcorner.com/article/asp-net-mvc-how-to-use-ajax-with-parameters/

I get better results using the $.post() method of the jquery library
here is an example:
$.post(`Services/Add/?name=${name}&price=${price}&about=${about}`,
function (insert) {
if (insert) {
$('#result').fadeIn(200).html(insert).fadeOut(200, () => {
location. Reload()
})
}
});
Source: JQuery Documentation about $.post()

Check if your controller is authorized or not. If you want the controller to work without any authorization then you have to add allowannoymous attribute on your controller since no access token is given in the ajax call.

Related

Model vs List<Model> when sending post request to controller using Ajax

I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.

Get data from ajax to mvc action

I want to send array of objects from ajax call to controller action.
On back-end side I have
container classes:
public class MyContainer
{
public string Id { get; set; }
public Filter[] Filters { get; set; }
}
public class Filter
{
public string Name { get; set; }
public string[] Values { get; set; }
}
and action:
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
On front-end side I have
$(document).on('click', 'mySelector', function (event) {
//Create first object
var firstIds = {};
firstIds.Name = "Custom Name 1";
firstIds.Values = GetIds('param1'); //this return an array of strings
//Create second object
var secondIds = {};
secondIds.Name = "Custome Name 2";
secondIds.Values = GetIds('param2'); //another array
var Id = $(this).attr('id'); //id of element
//Add objects to array
var filters = [];
filters.push(firstIds);
filters.push(secondIds);
$.ajax({
method: "GET",
url: baseUrl+"/MyAction",
//traditional: true, //I tried with and without that parameter
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
});
So if I use it like in example on top, container-object in action have Id value and have array of 2 elements in Filters, however both of them have Name and Values as null.
With traditional set to True, I got container.Id set but container.Filters = null.
Any suggestion?
Thank you.
Use a POST request in combination with JSON.stringify() method.
C#
[HttpPost]
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
JQUERY
$.ajax({
method: "POST",
url: baseUrl+"/MyAction",
data:JSON.stringify(
{
Id: Id,
Filters: filters
}),
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
Why do you need JSON.stringify() method ?
contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
You should use POST method instead of GET in ajax request. As you are posting data. and also your action should have [HttpPost] decorator.
$.ajax({
method: "POST",
url: baseUrl+"/MyAction",
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
Though its an old post, adding my bit to it. I would ask if you are returning a view from the action or not? here it seems like you are not returning a view but just wanting to update some data.
But in case you wanted to return a view, for e.g like showing some product info, then you would just pass the selected product's id to the action method, retrieve the related product information and then pass on this data as a model to the view, and then return the complete view. In this case you don't need a separate ajax call to process the data, instead just do it when you are requesting for the view itself (through the action method).
On the contrary if you already have the view rendered and are just wanting to change the data inside the current view then just resort to an ajax call to get the data without any view.
Hope it helps

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}

Ajax throwing error after calling controller

I am having some issues calling a controller method from my jquery ajax. The controller method is called and the data servername is passed in correctly. But, before my controller can return anything to the jquery, the jquery enters the error state.
Here is my jquery and controller code snippets:
$.ajax({
type: 'POST',
url: '#Url.Action("serverLookup", "QC")',
dataType: 'text',
data: { 'serverName': servername },
success: function (result) {
alert(result);
debugger;
},
error: function (result) {
debugger;
}
});
[HttpPost]
public ActionResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Content(data);
}
On top of everything. The result value given when the error is reached is not helpful at all either.
Send your response back as JsonResult
[HttpPost]
public JsonResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Json(data);
}
Return a Json:
return Json(new { result: data });
When you make an AJAX request to the controller, it needs a JsonResult.
I suppose that Your Content() return html. In that case You have to change dataType to html, Or change it according to your response.

MVC How to pass data from view to model using Ajax

Hello I'm posted a question asking what to use to send information from a view to a model. I realize that the info needs to be send to the controller and then to my model. I got some code that send info from my view to my controller:
Here is the Ajax:
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content fom the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
alert(data);
},
error: function (e) { alert(e); }
})
});
});
An this is the code in my controller:
[HttpPost]
public ActionResult processCommand(string cmd)
{
return Json(cmd);
}
I've tested it and send my input in json. However my problem is, I don't know how to take the string out of that and send it to my model. Please any help would be appreciated.
As stated in the comments to your question, the terminology you use is a little confusing, but if understood your question correctly, you want an action on your controller on the server to accept a 'command' and work with it.
The following post can be made, in order for the ajax post to successfully hit the action :
$('#cmdSend').click(function () {
var cmdInput = document.getElementById('cmdInput').value;
$.ajax({
url: 'terminal/sendInfo',
type: 'POST',
data: {cmd : cmdInput},
dataType: 'json',
success: function (data) {
//What you want to do with the returned string with data.cmd
}
});
});
The controller action would be like the following :
public class TerminalController : Controller
{
[HttpPost]
public JsonResult sendInfo(string cmd)
{
//Do what you want to do with 'cmd' here.
return Json(new { cmd = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps!

Categories