Passing dynamic objects from client-side to C# - c#

Passing dynamic objects from client-side to C#
hello friends,
i'm searching for passing a dynamic data, whatever data sent which is value type or reference type or both,
lets see a example as simple
client-side
1st request
var model = {
Id: 10,
Name: 'John'
Active: true
};
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: JSON.stringify(model)
});
2nd request
var model = {
Email: 'm#m.net'
CurrentSalary: 1500,
CurrencyType: 1
};
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: JSON.stringify(model)
});
3rd request
var id = '1e575923-d6cf-447e-9163-f7885655e4f5';
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: {Id : id}
});
server-side
public JsonResult GetData(dynamic model)
{
// my code here...
}
Question:
I need a way to receive a dynamic data.
Is it possible to send dynamic data from client-side(using jquery ajax) to Server-side C# ?!
Please let me know if you have any idea about this question.
Note: I will not vote down, for any answer
i use this for call server-side
var data = {
Name: 'Sam',
Age: "26"
};
$.ajax({
url: "http://localhost:8081/Home/PostData",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
alert(data);
},
error: (xhr, tt, tm) => errorHandler(xhr, tt, tm)
});
function errorHandler(xhr, tt, tm) {
console.dir(xhr, tt, tm);
};
Thank you so much, UW.

Related

C# and Ajax - Posting 2 values from JS to C#

I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
—- UPDATE ——
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}

Ajax error when there's a parameter in url

I have a ajax code that fills a dropdownlist and I use mvc c#.
When I call to my method from ajax and I have an url in the directions bar without parameters the code works correctly, but if I have a parameter in url in the directions bar this not working and appears this error:
"{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}".
Here's my code:
$.ajax({
url:"../Records/myList",
type: "POST",
dataType: 'json',
contentType: 'application/json',
// data: JSON.stringify(Data),
success: function (resul) {
Function(resul);
},
error: function (message) {
}
});
My url: http://localhost:123/Record/EditRecord ->> so it's works
My other url: http://localhost:123/Record/EditRecord/1 ->> It does not work like this
Thanks in advance.
From given second URL (which doesn't work) I assume that you want to use jQuery AJAX with HttpGet method. The URL pattern matches this route:
http://localhost:123/{controller}/{action}/{id}
which id treated as UrlParameter.
Hence you need to use action argument & data representing URL parameter values, like this example:
Controller
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Alternatively a direct usage of URL parameter is applicable for GET methods without specifying data content:
View (JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB: Use jQuery.get for simplified version:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS: This is an example for HTTP POST request if you're looking for proper POST method with AJAX.
Controller
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Reference:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
i cant see any fault in the code but i suggest to try let the param come with it's name at server either if you choose to use data propery (of ajax function):
{key1: 'value1', key2: 'value2'}
or you use string query:
page?name=ferret&color=purple
bacuse you've just say that first method was work i assume there is no need to check POST/GET method.
EDIT:
be award to this.

Passing arguments in jQuery post to a method in controller

In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});

Ajax not posting data to controller

I am posting data through ajax to a action, but the problem I am not able to get the data posted through ajax in my controller action. While debugging, the call gets transferred to action but I dont get anything in data not even 'null'.
here is my ajax call,
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: { country: 2, amount: 4.02 },
datatype:JSON,
success: function (data) {
alert("hiiii"+data);
}
});
and my action,
[HttpPost]
public JsonResult PostAmount(int country,double amount)
{
AllocationViewModel mod = new AllocationViewModel();
return Json(mod);
}
Try this:
var dataToPost = "{ country:'" + 2 + "', amount:" + 4.02 + "}";
$.ajax({
url: #Url.Action("PostAmount", "Deal")',
type: "POST",
dataType: 'json',
data: dataToPost,
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
alert("hi"+ data);
}
});
try the following:
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: { "country": "2", "amount": "4.02" },
datatype:JSON,
success: function (data) {
alert("hiiii"+data);
}
});
or the best solution is to save the values in an object and use the jquery function "stringify" and then send the values over. that should work.
try putting json in quotes
$.ajax({
type: 'POST',
url:'#Url.Action("PostAmount", "Deal")',
data: { country: "2", amount: "4.02" },
dataType:"json",
traditional:true,
success: function (data) {
alert("hiiii"+data);
}
});
You could also use JSON.stringify(yourObject) on your object to make it a JSON object. This makes it easier to create objects in javascript and pass then into the data parameter of your post request.
Also use a string for the datatype parameter (https://api.jquery.com/jquery.post/), as suggested in the answers above.
var dataToPost = { country: 2, amount: 4.02 };
$.ajax({
type: 'POST',
url:' #Url.Action("PostAmount", "Deal")',
data: JSON.stringify(dataToPost),
datatype: 'json',
success: function (data) {
alert("hiiii"+data);
}
});
The other way around is JSON.parse(yourJsonObject). This way you can parse a JSON string into a Javascript object.

MVC posting form and extra param to an MVC controller using Ajax

I need to find a way to post a serialized form and an extra param to controller via ajax request. I can use serialize() on the form, or just send object with params, but cannot send both. How would I accomplish this?
For example I want my controller params to be as follows:
myaction(int siteID, Model model).
Pass what ever extra parameters you want along with form data as follows:
$.ajax({ type: 'POST',
url: "/MyController/Process",
data: $("form").serialize() + '&id=12345' ,
success: function () { alert("Successful"); },
dataType: "json"
});
Hope this helps..
You need to use something like this:
var dataToPost = $('#formID').serialize() + "&siteID=" + "23";
Now use this dataToPost variable in jquery ajax method like this:
$.ajax({
url: //url,
type: //'POST',
dataType: //'html',
async: true,
data: dataToPost,
cache: false,
}).success(function (response, status, xhr) {
}).fail(function (e) {
console.log(e);
});

Categories

Resources