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.
Related
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:
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
Code to update with a custom button in the calendar:
myCustomButton: {
text: 'Save Events',
click: () => {
var allevents = calendar.getEvents();
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: allevents,
url: '/Wishes/Individual/Update',
headers: {
'RequestVerificationToken': '#antiforgery.GetAndStoreTokens(HttpContext).RequestToken'
},
success: function (response) {
alert: ('success');
},
failure: function (response) {
alert: ('failure');
}
});
}
},
According to your description and code, it seems that you'd like to post all events within FullCalendar to your Razor Page handler by making AJAX Post Request(s), and then save/update events on database.
To achieve the requirement, you can refer to the following example.
On JavaScript Client
customButtons: {
myCustomButton: {
text: 'Save Events',
click: function () {
var allevents = calendar.getEvents();
var events = [];
$.each(allevents, function (index, event) {
//console.log(event);
// include only expected data (such as title, start and end etc) in json object `newevent`
// instead of all information of calendar event
var newevent = { "title": event.title, "start": event.start, "end": event.end };
events.push(newevent);
});
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(events),
url: '/Wishes/Individual/Update',
headers: {
'RequestVerificationToken': '#antiforgery.GetAndStoreTokens(HttpContext).RequestToken'
},
success: function (response) {
alert: ('success');
},
failure: function (response) {
alert: ('failure');
}
});
alert('clicked the custom button!');
}
}
},
Razor page handler method
public IActionResult OnPostUpdate([FromBody]List<Event> events)
{
//code logic here
return Content("ok");
}
Custom Event class
public class Event
{
public string title { get; set; }
public string start { get; set; }
public string end { get; set; }
// defind other properties
// such as groupId, url etc based on your requirements
}
Test Result
I am posting the data through ajax from my form but it is going null always.
What i am doing is:-
In my View Page:-
<script>
$(document).ready(function () {
$("#blogForm").submit(function (e) {
e.preventDefault();
alert("YOO");
debugger;
var fileInput = $('#authorImage')[0];
var authorImage = fileInput.files[0];
//var blogFile = $("#blogImages")[0];
//var blogImages = blogFile.files[0];
var editor = new Quill('#editor');
var content = editor.getContents();
var BlogData =
{
Title: $(".txttitle").val(),
DestinationId: $("#ddlDesignation").val(),
Category: $("#ddlCategory").val(),
Author: $(".txtauthor").val(),
AuthorDetail: $(".txtauthorDetail").val(),
Date: $(".txtDate").val(),
Contents: content
}
var CreateEditBlogsViewModel =
{
BlogDTO: BlogData
}
var param = JSON.stringify(CreateEditBlogsViewModel);
//doing ajax request
$.ajax({
contentType: "application/json",
method: "POST",
dataType:"JSON",
url: "#Url.Action("Create", "Blog")",
data: param,
success: function () {
alert("success");
},
error: function () {
alert("Error");
}
});
});
});
</script>
In my Controller:
[HttpPost]
public IActionResult Create(CreateEditBlogsViewModel BlogDTO,IFormFile authorimage,IFormFile images)
{
if (ModelState.IsValid)
{
_blogservice.Insert(BlogDTO.BlogDTO);
}
//rebinding values
BlogDTO.DestinationSelectList = GetDestinationSelectList();
BlogDTO.BlogCategorySelectList = GetBlogCategorySelectList();
return View();
}
My Model looks like this:
public class CreateEditBlogsViewModel
{
public BlogsDTO BlogDTO { get; set; }
public List<SelectListItem> DestinationSelectList { get; set; }
public List<SelectListItem> BlogCategorySelectList { get; set; }
}
I have also tried applying [FromBody] in controller,but no luck. I also have to post 2 seperate images also but at first i only want that data then i will try to post image.
Please Help.
Edit : I have solved this by using CKEditor in place of quill editor and now I am posting all the data using form.
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);
}