How to Send Json String to Controller in mvc4 and Deserialize json - asp.net-mvc-4

I have the json object like below
Extension = {
"BookMarks":
[{"Name":"User1","Number":"101"},
{"Name":"User2","Number":"102"},
{"Name":"User3","Number":"103"}]}
I want to send this json string to my controller Action method and Deserialize the data
I want to pass the data to the partialview
public ActionResult ExtensionsDialog(var data)
{
return PartialView(data);
}
Any help
Thanks in advance..

In your View:
function SendData(){
var dataToSend = JSON.stringify(data);
$.ajax({
type: "POST",
url: '#Url.Action("YourAction", "YourController")',
dataType: "json",
data: dataToSend,
contentType: "application/json; charset=utf-8",
});
}
$("#Updatebtn").click(function () {
sendData();
});
In you Model:
public class YourModel
{
public String Name { get; set; }
public int Number { get; set; }
}
In your Controller:
[HttpPost]
public ActionResult YourAction()
{
var resolveRequest = HttpContext.Request;
List<YourModel> model = new List<YourModel>();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
model = (List<YourModel>)serializer.Deserialize(jsonString, typeof(List<YourModel>);
}
//Your operations..
}
Hope this helps.

I don't think you have to read the input stream yourself. If you provide a model the binder should do it for you.
In your code behind:
public class StatusInfo
{
public int ItemId { get; set; }
public int StatusId { get; set; }
}
[HttpPost]
public ActionResult EditStatus(StatusInfo info)
{
DoSomethingInteresting(info.ItemId, info.StatusId);
return new EmptyResult();
}
And just use the jQuery ajax function like so:
function changeStatus(itemId, statusId) {
var postData = { "ItemId": itemId, "StatusId": statusId };
$.ajax({
url: "/Item/EditStatus",
type: "POST",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
console.log("success updating status.");
},
error: function () {
console.log("error updating status.");
}
});
}

You can call the action and pass values like this. Just substitute your data with the data I have in the data section.
$.ajax({
url: '/Schedule/Schedule/Create',
type: 'POST',
cache: false,
datatype: JSON,
data: {
scheduleName: ScheduleName,
description: Desc,
Hol_Type: JSON.stringify(holidaytype),
Start_Date: start_date,
End_Date: end_date,
Start_Time: StartTime,
End_Time: EndTime,
days: JSON.stringify(days),
rec_type:1
},
success: function (data, status) {}});

You can pass your data via an ajax call like this :
$.ajax({
url : "#Url.Action("YourMethod", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({Extension: data})
}).done(function (result) {
//Check if it's OK
}).fail(function (result) {
//Check if it is not OK
}).always(function() {
//Some code executed whatever success or fail
})
.done, .fail and .always are not compulsory, it's just better in my opinion.
Then use it in your Controller as you've done.
It should be OK.

Your script should be like:
Extension = {"BookMarks":[{"Name":"User1","Number":"101"},{"Name":"User2","Number":"102"},{"Name":"User3","Number":"103"}]}
$.ajax({
url : "#Url.Action("ExtensionsDialog", "Controller")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : {"data" : Extension }
});
Action method is same.
public ActionResult ExtensionsDialog(var data)
{
return PartialView(data);
}

Related

ASP.NET Core MVC : HTTP POST method not return to view

View:
#Html.DropDownList("bolumler", null, "lutfen bolum secin",
new {#class = "form-control",
#onchange="SelectedIndexChanged(this)"})
<script type="text/javascript">
function SelectedIndexChanged(item) {
var value = item.value;
$.ajax({
type: "POST",
url: "#Url.Action("GoTo")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data:JSON.stringify( value ),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
Controller:
[HttpPost]
public async Task<IActionResult> GoTo([FromBody] string d)
{
var personeller = await _iluPersonelService.getPersonelWithDepartment(d);
List<SelectListItem> valuesForPersonel = (from x in personeller
select new SelectListItem
{
Text = x.Name,
}).ToList();
ViewBag.personeller = valuesForPersonel;
return View();
}
I can't figure out this problem. In .cshtml side, I change dropdownlist selection item and controller post method triggering. I did some operations on the data and I want to return new data to view and display it.
Note: there are no changes on the page and it is not refreshed
Do you want to alert(data) ?
If so , do you want the below way ?
change the action like below:
[HttpPost]
public async Task<IActionResult> GoTo([FromBody] string d)
{
...
return Json(valuesForPersonel);
}
public IActionResult Goto()
{
return View();
}
2.In the view:
change the success method code in your ajax:
$.ajax({
type: "POST",
url: "#Url.Action("GoTo")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(value),
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].text);
window.location.href = "https://localhost:7169/RtCd/Goto";
}},
failure: function (errMsg) {
alert(errMsg);
}
});
result:

ASP.NET Core AJAX POST not returning error, however, not saving data

I am using a button OnClick event to try and save a record to a database using AJAX in ASP.NET Core. The function is not returning an error, however, the data is not being saved. I am just trying to test with hard coded data first. A record with AdapollingProjectProcessStatusId = 1 exists in the database.
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
contentType: "application/json",
data: JSON.stringify({ "id": 1, "status": 'test'}),
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
LiveAdapollingProjectProcessStatusController:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
return Json(processstatus);
}
LiveAdapollingProjectProcessStatus.cs:
namespace CPSPMO.Models.PMO
{
public partial class LiveAdapollingProjectProcessStatus
{
public int AdapollingProjectProcessStatusId { get; set; }
public string AdapollingProjectProcessStatus { get; set; }
}
}
Please let me know if you are able to help me with this AJAX Post.
Thanks
Not sure how do you store it to the database, but the way you pass parameter to backend by ajax should be like below:
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
//contentType: "application/json", //remove this...
data:{ "id": 1, "status": 'test'}, //modify here...
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
After reviewing the comments regarding missing code for saving the data in the database, I modified the controller:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
var result = _context.LiveAdapollingProjectProcessStatuses.Update(processstatus);
_context.SaveChanges();
return Json(processstatus);
}
It is saving the data to the database now. Thanks for the help

Can not pass list of object to method by AJAX

I'm sorry that this question has been too long. I have consulted a lot of articles on Stack Overflow but it doesn't run on my source code. I am using ASP.NET Core MVC.
My AJAX
function PayAjax(orders, payment, note) {
orders = [{ 'id': 1, 'quantity': 2 }, { 'id': 3, 'quantity': 4 }];
var formData = new FormData();
formData.append('orders', orders);
formData.append('payment', payment);
formData.append('note', note);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
}
My controller
[HttpPost]
public async Task<IActionResult> Pay(List<Order> orders, int payment, string note)
{
...
}
}
My Object Order
public class Order
{
public int Id { get; set; }
public int Quantity { set; get; }
}
My data is coming to controller but I don't access to values.
Orders always have count = 0.
Even if I pass JSON like below, controller orders is always empty
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data: JSON.stringify({ 'orders': orders, 'payment': payment, 'note': note}),
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
Try to put data into formData one by one:
function PayAjax(orders, payment, note) {
orders = [{ 'id': 1, 'quantity': 2 }, { 'id': 3, 'quantity': 4 }];
var formData = new FormData();
for (var i = 0; i < orders.length; i++) {
formData.append("orders[" + i + "].Id", orders[i].id);
formData.append("orders[" + i + "].Quantity", orders[i].quantity);
}
formData.append('payment', payment);
formData.append('note', note);
$.ajax({
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
}
You can wrap these parameter request to single object
[HttpPost]
public async Task<IActionResult> Pay(PayRequest request)
public class PayRequest
{
public List<Order> orders {get; set;}
public int payment {get; set;}
public string noteget; set;}
}
you should get parameters by [FromForm] annotation and convert object to FormData if you want post it using formData
public ActionResult Pay([FromForm] List<Order> orders, [FromForm] int payment, [FromForm] string note) {
}
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key => {
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
});
} else {
const value = data == null ? '' : data;
formData.append(parentKey, value);
}
}
function jsonToFormData(data) {
const formData = new FormData();
buildFormData(formData, data);
return formData;
}
function pay() {
orders = [{ 'Id': 1, 'Quantity': 2 }, { 'Id': 3, 'Quantity': 4 }];
PayAjax(orders, 2000, 'Hello')
}
function PayAjax(orders, payment, note) {
const dataToSend = {
orders,
payment,
note
}
const data = jsonToFormData(dataToSend)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data,
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
}

Why is the model binding not working? ASP.NET Core 5.0 RazorPages

ASP.NET Core 5.0 Razor Pages.
When posting the array, the model is not binding - value is showing empty array.
This is a JSON array posted using Ajax -
[
{ "Order":1, "FileName":"bbed5ecf-4133-4681-b0f3-c11366ad3186.jpg" },
{ "Order":2, "FileName":"737e60dc-0631-493d-947d-2f5948d7818c.jpg" },
{ "Order":3, "FileName":"6c76f9d1-44bd-4b80-926e-2ce4307eb30b.jpg"}
]
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(newOrderDictionary),
success: function (response) {
}
});
}
RazorPage action Method
public async Task OnPostAsync(ImageOrder[] data)
{
}
public class ImageOrder
{
public int Order { get; set; }
public string FileName { get; set; }
}
The data parameter of the POST should be the object value, not a stringified version of it. Try changing to:
...
data: newOrderDictionary,
...
Assuming newOrderDictionary is an array.
Considering using post to pass data, you need to add contentType:"application/json" in ajax.
$.ajax({
type: "POST",
url: "/?handler",
dataType: "json",
contentType:"application/json",
//...
});
In addition, add [FromBody] in the bakend.
public async Task OnPostAsync([FromBody]ImageOrder[] data)
{
}
Then, it can get the data.
Turns out that this works :
public async Task OnPostAsync(ImageOrder[] order)
{
}
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: {
order: newOrderDictionary
},
success: function (response) {
}
});
}

How do I send the JavaScript Array to the Controller from Ajax

Cannot get object values in the controller from the ajax post.
I have a jQuery data table with the first column being checkbox's and I need to return the selected row ids to the controller. I can get everything I need but it is always null in the controller.
Model:
public class Values
{
public Guid ID { get; set; }
}
View JS & Ajax on button click:
function SubAll() {
var values = [];
$('#timesheet').find('input[type="checkbox"]:checked').each(function (index, rowId) {
//this is the current checkbox
var temp = $(this).closest('tr').attr('id');
if (String(temp) === String("undefined")) {
//skip; it is the select all box
}
else {
//push to array
values.push(temp);
}
});
console.log(values);
var data = { ID: values };
console.log(data);
$.ajax({
url: "#Url.Action("ApproveAllTimesheets", "Admin")",
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public void ApproveAllTimesheets(List<Values> value)
{}
On button click the array 'values' gets filled with the id if a box was selected (works fine), then it is turned into an object 'data' to match the method signature and model and stringify'd. When the breakpoint is hit on the controller method the values are never there. What am I missing?
**UPDATE:**
function SubAll() {
var values = [];
$('#timesheet').find('input[type="checkbox"]:checked').each(function (index, rowId) {
//this is the current checkbox
var temp = $(this).closest('tr').attr('id');
if (String(temp) === String("undefined")) {
//skip; it is the select all box
}
else {
//push to array
values.push({ Id: temp });
}
});
console.log(values);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
data: values,
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
**Method Signature:**
public IActionResult ApproveAllTimesheets( List<Value> values)
**Class**
public class Value
{
public Guid ID { get; set; }
}
UPDATE #3
Model:
public class Value
{
public string TimeId { get; set; }
}
Ajax:
function SubAll() {
//var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var dataJSON = { TimeId: "test" };
console.log(dataJSON);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(dataJSON),
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller:
public ActionResult ApproveAllTimesheets([FromBody]Value information)
You should insert the ids like javascript normal objects :
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe8",
});
Code below is for your reference :
function SubAll() {
var values = [];
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe6",
});
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe7",
});
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe8",
});
$.ajax({
type: "POST",
url: "/Admin/ApproveAllTimesheets",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(values),
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller :
public void ApproveAllTimesheets([FromBody]List<Values> value)
{
}
Model :
public class Values
{
public Guid ID { get; set; }
}
If this is your JSON
{ <-- This here is the start of your object
"id": 1;
}
This would need to get bound to a Model
class AnyModel {
public int Id {get; set;}
}
If you have a list in JSON
{
[
...Some objects
]
}
You would need to accept a model of in your controller
class AnyModel {
public List<SomeOtherModel> ListObject {get; set;}
}
Update
You want to store the list of 'Values' in another model.
class Value {
public Guid Id {get;set;}
}
class ValueContainer {
public List<Value> Values {get; set;}
}
Now you want to bind your JSON to your ValueContainer object. When you send JSON you need the [FromBody] for the JSON to get bound to your Model.
public IActionResult ApproveAllTimesheets([FromBody] ValueContainer values) {}
Update 2
Apologies looking through your JS code (old one) a little bit closer you should be using the following structure:
class ValueContainer {
public List<Guid> Id {get; set;}
}
List<Guid> is your values array which you bind to id in your JSON object. Controller stays the same.
public IActionResult ApproveAllTimesheets([FromBody] ValueContainer values) {}
So my Update #3 is working and now I have a different issue so I will post a new question for that.