Ajax POST not hitting controller break point - c#

My ajax POST request does'nt seem to be hitting my contoller, although i have used other Ajax post requests in my application this one doesnt seem to be working. My first throught was the datatypes within the model were not strings but other than that i can't seem to figure out why it isnt working.
Model
public class AppointmentViewModel
{
public List<DTO.Appointment> appointments { get; set; }
public DTO.Appointment appointment { get; set; }
public int AppointmentId_Input { get; set; }
public string AppointmentTitle_Input { get; set; }
public string AppointmentName_Input { get; set; }
public DateTime AppointmentStartTime_Input { get; set; }
public DateTime AppointmentEndTime_Input { get; set; }
public int AppointmentType_Input { get; set; }
public List<DTO.AppointmentType> appointmentTypes { get; set; }
}
Controller:
public ActionResult AddAppointment(Models.AppointmentViewModel avm)
{
BLL.FTSPManager fm = new BLL.FTSPManager();
DTO.Appointment a = new DTO.Appointment()
{
Id = avm.AppointmentId_Input,
Info = avm.AppointmentTitle_Input,
Name = avm.AppointmentName_Input,
StartTime = avm.AppointmentStartTime_Input,
EndTime = avm.AppointmentEndTime_Input,
type = new DTO.AppointmentType()
{
Id = avm.AppointmentType_Input
}
};
return Json(avm);
}
Ajax Request:
$('#btnAdd').click(function () {
var id, title, name, startTime, endTime, AppointmentType
id = $('#hdnAppointmentId').val();
title = $('#txtTitle').val();
name = $('#txtName').val();
startTime = $('#txtStartDate').val();
endTime = $('#txtEndDate').val();
AppointmentType = $('#drptype').val();
var JsonData = {
AppointmentId_Input: id,
AppointmentTitle_Input: title,
AppointmentName_Input: name,
AppointmentStartTime_Input: startTime,
AppointmentEndTime_Input: endTime,
AppointmentType_Input: AppointmentType
};
$.ajax({
type: "POST",
url: '#Url.Action("AddAppointment", "Admin")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(JsonData),
dataType: "json",
success: function (data) {
return false;
}
});
})

You can use a FormData function. I can give for you a working example:
Html code(button, without other "input" tags:
<div class="form-group">
<button type="button" id="dataSend">DataSend</button>
</div>
Javascript code:
$("#dataSend").on('click', function () {
var formData = new FormData();
formData.append('Image', $('#file')[0].files[0]);
formData.append('Title', document.getElementById('Title').value);
formData.append('Description', document.getElementById('Description').value);
formData.append('Topic', document.getElementById('Topic').value);
formData.append('AdditionalFields', JSON.stringify(obsFields));
$.ajax({
contentType: false,
processData: false,
type: 'POST',
url: '/Collection/Create',
data: formData,
success: function () {
console.log("success.");
},
error: function () {
console.log("error.");
},
});});
C# code(controller):
[HttpPost]
public async Task<IActionResult> Create(DataForm AllData)
{
return RedirectToAction("Action-method", "Controller");
}
C# code(model):
public class DataForm
{
public string Title { get; set; }
public string Description { get; set; }
[EnumDataType(typeof(Topic))]
public Topic? Topic { get; set; }
public IFormFile Image { get; set; }
public string AdditionalFields { get; set; }
}
Field "AdditionalFields" is a son converted and in Controller it deserialized to 'List list'.
I'm waiting for your questions.

Related

JSON.stringify Passing Into Razor-Page As Null

I have a asp.net core razor-page where I am trying to read the data off of a table and pass it into a my controller so that I can process changes made in the table. I've checked other similar questions on this site like this one: MVC model is null when posting json in ASP.Net Core
but I keep getting a null value in the razor-page. I'm posting the relevant code below. If there is something else that you need to see please let me know.
Ajax Call Below:
//--------------------------------------------------------------------
// Load Up An Array and Pass the Data To The Razor Page
//--------------------------------------------------------------------
$('#UpdateScoresButton').click(function () {
// Store Data in an Array
var enteredScores = new Array();
// Loops through whole table
$("#table tbody tr").each(function () {
// Grabs Each Row
var row = $(this);
var score = {};
score.DeputyID = row.find("td").eq(0).html();
score.DivisionID = row.find("td").eq(1).html();
score.QuarterID = row.find("td").eq(2).html();
score.PrimaryModelID = row.find("td").eq(3).html();
score.SecondaryModelID = row.find("td").eq(4).html();
score.ShotgunModelID = row.find("td").eq(5).html();
score.RifleModelID = row.find("td").eq(6).html();
score.PrimaryFirstScoreID = row.find("td").eq(7).html();
score.PrimarySecondScoreID = row.find("td").eq(8).html();
score.PrimaryThirdScoreID = row.find("td").eq(9).html();
score.SecondaryScoreID = row.find("td").eq(10).html();
score.ShotgunScoreID = row.find("td").eq(11).html();
score.RifleScoreID = row.find("td").eq(12).html();
enteredScores.push(score);
});
$.ajax(
{
url: '/EnterScores/Enter_Shooter_Scores?handler=InsertUpdateAndReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'application/json; charset=utf-8',
data: JSON.stringify(enteredScores),
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
error: function (result, exception) {
console.log(result);
// Your error handling logic here..
},
});
});
Here is the razor-page code:
public JsonResult OnPostInsertUpdateAndReloadData([FromBody] List<EnteredScores> enteredScores)
{
var test = enteredScores;
return new JsonResult(new { pass = "Pass" }); ;
}
My EnteredScores Class :
public class EnteredScores
{
public int DeputyID { get; set; }
public int DivisionID { get; set; }
public int QuarterID { get; set; }
public int PrimaryModelID { get; set; }
public int SecondaryModelID { get; set; }
public int ShotgunModelID { get; set; }
public int RifleModelID { get; set; }
public int PrimaryFirstScoreID { get; set; }
public int PrimarySecondScoreID { get; set; }
public int PrimaryThirdScoreID { get; set; }
public int SecondaryScoreID { get; set; }
public int ShotgunScoreID { get; set; }
public int RifleScoreID { get; set; }
}
Since the properties in EnteredScores are int type.You need to pass int type data to handler.Try to change
score.DeputyID = row.find("td").eq(0).html();
score.DivisionID = row.find("td").eq(1).html();
score.QuarterID = row.find("td").eq(2).html();
score.PrimaryModelID = row.find("td").eq(3).html();
score.SecondaryModelID = row.find("td").eq(4).html();
score.ShotgunModelID = row.find("td").eq(5).html();
score.RifleModelID = row.find("td").eq(6).html();
score.PrimaryFirstScoreID = row.find("td").eq(7).html();
score.PrimarySecondScoreID = row.find("td").eq(8).html();
score.PrimaryThirdScoreID = row.find("td").eq(9).html();
score.SecondaryScoreID = row.find("td").eq(10).html();
score.ShotgunScoreID = row.find("td").eq(11).html();
score.RifleScoreID = row.find("td").eq(12).html();
to
score.DeputyID = parseInt(row.find("td").eq(0).html());
score.DivisionID = parseInt(row.find("td").eq(1).html());
score.QuarterID = parseInt(row.find("td").eq(2).html());
score.PrimaryModelID = parseInt(row.find("td").eq(3).html());
score.SecondaryModelID = parseInt(row.find("td").eq(4).html());
score.ShotgunModelID = parseInt(row.find("td").eq(5).html());
score.RifleModelID = parseInt(row.find("td").eq(6).html());
score.PrimaryFirstScoreID = parseInt(row.find("td").eq(7).html());
score.PrimarySecondScoreID = parseInt(row.find("td").eq(8).html());
score.PrimaryThirdScoreID = parseInt(row.find("td").eq(9).html());
score.SecondaryScoreID = parseInt(row.find("td").eq(10).html());
score.ShotgunScoreID = parseInt(row.find("td").eq(11).html());
score.RifleScoreID = parseInt(row.find("td").eq(12).html());
And since you passed data is json type,you need to add contentType: "application/json", to your ajax like this:
$.ajax(
{
url: '/EnterScores/Enter_Shooter_Scores?handler=InsertUpdateAndReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
contentType: "application/json",
dataType: 'application/json; charset=utf-8',
data: JSON.stringify(enteredScores),
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
error: function (result, exception) {
console.log(result);
// Your error handling logic here..
},
});
result:
Your issue is likely due to model binding failing. Looking over this code, the first issue I'd address is the difference been the Javascript object names [that you're passing up to your C#/MVC action] and the "EnteredScores" model/class properties. The easiest refactor would be to edit your Javascript code like so:
score.DeputyID = row.find("td").eq(0).html();
score.DivisionID = row.find("td").eq(1).html();
score.QuarterID = row.find("td").eq(2).html();
etc.
Change the above [your orginal code] to the below [my refactor of that code], just make sure you update all fields so they match.
DeputyID = row.find("td").eq(0).html();
DivisionID = row.find("td").eq(1).html();
QuarterID = row.find("td").eq(2).html();
etc.

WebMethod Files Upload

I need to create method to upload multiple files.
Here is my backend model that is passed as an public void ImageUpload(IEnumerable<ImageModel> images)
public class ImageModel
{
public int EntityId { get; set; }
public string FileName { get; set; }
public string AltText { get; set; }
public byte[] Content { get; set; }
public int ImageRoomId { get; set; }
}
From the js I send formdata and is looks like this
But i get System.IndexOutOfRangeException: Index was outside the bounds of the array.
I can't understand where is the mistake. Do I need to use any other content type?
UPDATE
[WebMethod]
public string developmentimageupload(ImageModel[] file)
{
return "Ok";
}
JS:
var formData = new FormData();
var formFields = container.querySelectorAll('input[type=text], select');
for(i = 0; i < fileList.length; i++){
formData.set('File[' + i + '].Content', fileList[i]);
formData.set('File[' + i + '].FileName', fileList[i].name);
}
for(var i = 0; i < formFields.length; i++){
formData.set(formFields[i].name, formFields[i].value);
}
$.ajax({
url: window.siteAdminProperties.Feeds.DevelopmentBulkImagesUploadUrl,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
$('.js-images-uploader').hide();
$('.js-images-uploaded').show();
}
});

JSON stringify not serialising ? Bind issue

In the controller WidgetConfigurationRequestVM request object
is returning 3 properties (lists) as null
jurisidctions
tags
workareas
I have binded this in the view and I am sure there is data set. They have same method types IEnumerable, why companyid binding and the other properties not binding in WidgetConfigurationRequestVM? Thank you for help!
API Controller:
[Route("api/track/v1/taxibriefing")]
public async Task<TaxiContainerModel> Post([FromBody] WidgetConfigurationRequestVM request)
{
request.Jurisidctions/tags/workareas = null?
request.companyId = exists
}
JS:
taxiBriefingButton.click(function (e) {
e.preventDefault();
var widgets = taxiConfigurationContainer.serialize();
var workAreaRefs = $(this).data("workarearefs");
var jurisdictions = $(this).data("jurisdictions");
var tags = $(this).data("tags");
var preset = $(this).data("preset");
createPdf($(this).data('companyid'), widgets, $('#notes').val(), workAreaRefs, jurisdictions, tags);
});
JS create PDF button:
function createPdf(companyId, widgets, notes, workAreaRefs, jurisdictions, tags) {
var doc = new PDFDocument({
bufferPages: true,
size: [842, 595]
});
window.dispatchEvent(GeneratingTaxiBriefingEvent);
var xhr = new XMLHttpRequest();
xhr.open('GET', '/taxiFonts/Roboto-Light.ttf', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (this.status == 200) {
doc.registerFont('Roboto', xhr.response);
$.ajax({
type: 'POST',
url: '/api/track/v1/taxibriefing',
contentType : 'application/json',
data: JSON.stringify({ CompanyId: companyId, Notes: notes, Configuration: widgets, Workareas: workAreaRefs, Jurisdictions: jurisdictions, Tags: tags }),
dataType: 'json',
success: function (result) { GeneratePDF(doc, result); }
});
}
};
xhr.send();
}
View:
#model Areas.Track.Models.TrackVM
<button id="taxi-briefing" class="btn btn-danger" data-preset="#Model.Filter.DatePreset" data-workarearefs="#Model.Filter.WorkareaRefs" data-jurisdictions="#Model.Filter.JurisdictionRefs" data-tags="#Model.Filter.TagsRefs" data-companyid="#Model.Filter.FirmRefs.First()">Create PDF</button>
Viewmodel:
public class WidgetConfigurationRequestVM
{
public int CompanyId { get; set; }
public string Notes { get; set; }
public IEnumerable<WidgetConfigurationVM> Configuration { get; set; }
public IEnumerable<int> Workareas { get; set; }
public IEnumerable<int> Jurisdictions { get; set; }
public IEnumerable<int> Tags { get; set; }
}

How to send a model which consist generic list from ajax call in mvc C#

I am trying to call the controller from ajax and sending model data which consist some list of data inside it. I am getting the count correct for them but inside the list properties are coming null.
Controller:
public JsonResult InsertorUpdate(IncidentEdit incident)
{
try
{
SrvincidentDtls.TicketNo = incident.TicketNo;
SrvincidentDtls.Priority = incident.Priority;
SrvincidentDtls.Status = incident.Status;
SrvincidentDtls.Title = incident.Title;
SrvincidentDtls.IsActive = incident.IsActive;
List<Comments> lstComm = new List<Comments>();
if(incident.CommentList!=null )
{
foreach (var comm in incident.CommentList)
{
Comments Comm = new Comments();
Comm.Comment = comm.Comments;
Comm.AddedBy = comm.AddedBy;
Comm.AddedBy_ID = comm.AddedBy_ID;
Comm.CreatedDate = comm.CreatedDate;
lstComm.Add(Comm);
}
}
SrvincidentDtls.Comments = lstComm.ToArray();
SrvincidentDtls.Description = incident.Description;
var result=proxyService.InsertorUpdateIncidentDetails(SrvincidentDtls);
return Json(new { success = true, jvalue = result }, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
throw ex;
}
}
Model:
public class IncidentEdit
{
public string Title { get; set; }
public string Description { get; set; }
public bool IsActive { get; set; }
public string Status { get; set; }
public string Priority { get; set; }
public List<IncidentComments> CommentList { get; set; }
}
Generic Class:
public class IncidentComments
{
public string Comments { get; set; }
public string AddedBy { get; set; }
public string AddedBy_ID { get; set; }
public DateTime CreatedDate { get; set; }
}
Ajax call:
function InsertOrUpdate(){
incidentDetails = {
Title: $("#txtTitle").val(),
Description: $("#txtDescription").val(),
Priority: $('#selPriority option:selected').val(),
Status: $('#selStatus option:selected').val(),
IsActive: 1,
CreatedDate :$('#spncrtdDt').text(),
CommentList:PopulateCommentList()
};
$.ajax({
type: "Get", //HTTP POST Method
url: insertORupdatUrl, // Controller/View
data: {incident:incidentDetails},
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
}
js function:
function PopulateCommentList() {
var CommentList = [];
var dtTable = $('#dvCommentTbl').DataTable();
for (var i = 0; i < 10; i++) {
if (dtTable.row(i).data() != "" && dtTable.row(i).data() != null && dtTable.row(i).data() != undefined) {
CommentList.push({
Comments: dtTable.row(i).data()[1],
AddedBy: dtTable.row(i).data()[2],
AddedBy_ID: dtTable.row(i).data()[0],
CreatedDate: dtTable.row(i).data()[3]
});
}
}
return CommentList;
}
the count for comment list is coming fine but the data like Added_By,comments,Created Dtae all coming null.
Plz help.
You can take a variable like
var commlist=PopulateCommentList();
then populate it in your model json:
incidentDetails = {
Title: $("#txtTitle").val(),
Description: $("#txtDescription").val(),
Priority: $('#selPriority option:selected').val(),
Status: $('#selStatus option:selected').val(),
IsActive: 1,
CreatedDate :$('#spncrtdDt').text(),
CommentList:commlist
};
it will work as it work for me.

Model is null from Json object

So when I set the javascript ReminderModel object properties this will work and my controller will receive the object if I set LeadId and StaffId to 1, but as soon as I turn them into strings the controller receives a null object.
I'm not sure what's going on, it might be a problem with the quotes?
My view code
var ReminderModel = {
"LeadId": "#Model.Id",
"StaffId": "1a53c286-b17e-4afd-9ccb-684fd1a92f7b",
"Subject": "Call Back",
"Time": "iTime",
"Date": "iDate"
};
$.ajax({
url: "#Url.Action("SetReminder","Appointment")",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(ReminderModel),
success: function (valid) {
if (valid) {
//show that id is valid
} else {
//show that id is not valid
}
}
});
My controller Method
[HttpPost]
public async Task<ActionResult> SetReminder([FromBody] ReminderViewModel viewModel)
{
using (var db = new LeadCoreDbContext())
{
DateTime dt = DateTime.MinValue;
DateTime.TryParse($"{viewModel.Date} {viewModel.Time}", out dt);
if (dt == DateTime.MinValue)
throw new Exception("Failed to set reminder");
var reminder = new Reminder
{
Deleted = false,
LeadId = viewModel.LeadId,
Subject = viewModel.Subject,
TimeToRemind = dt,
StaffId = viewModel.StaffId
};
db.Reminder.Add(reminder);
await db.SaveChangesAsync();
}
return Content("received");
}
Here is the model
public class ReminderViewModel
{
public int Id { get; set; }
public int LeadId { get; set; }
public int StaffId { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public string Subject { get; set; }
}

Categories