jQuery Array is not posting to ASP.NET MVC controller - c#

I am having a hard time posting a list of arrays from my view to the controller. Every other value is coming through.
Can someone spot what is wrong with my code?
Controller:
public ActionResult SaveProgress(BBCRMSurveyVM model)
{
try
{
return Json(new { success = true });
}
catch (Exception e)
{
return Json(new { success = false, msg = e.Message });
}
}
Main view model:
public string ImplementationProcessFeelWasSuccessful { get; set; }
public string ImplementationProcessAdviceOtherFederations { get; set; }
public List<AdditionalTechnologyVM> AdditionalTech = new List<AdditionalTechnologyVM>();
AdditionalTechVM:
public class AdditionalTechnologyVM
{
public string PlatformName { get; set; }
public string BusinessPurpose { get; set; }
public bool? FullyIntergrated { get; set; }
public bool? PartiallyIntergrated { get; set; }
}
JS file:
function onAddButtonClickEvent() {
additionaltechs.push({
'PlatformName': platformNameAT,
'BusinessPurpose': businessPurposeAT,
'FullyIntergrated': intergrated == "Fully" ? true : false,
'PartiallyIntergrated': intergrated == "Partially" ? true : false
});
}
function SaveProgress() {
var formData = $('#wizard').serializeArray();
//if (additionaltechs.length > 0) {
// for (var x = 0; x < additionaltechs.length; x++) {
// formData[formData.length] = { name: "AdditionalTech", value: JSON.stringify(additionaltechs[x]) };
// }
//}
formData[formData.length] = { name: "AdditionalTech", value: additionaltechs };
$.each(formData, function (index, field) {
if (field.name.search('Budget') > 0) {
field.value = field.value.replace('$', '').replace(/,/g, '');
}
});
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
The output in the console:
The list count is always 0?

I think you made this more complicated than you needed it to be. :)
Ultimately, it looks like your controller method is taking a single model, not an array. Thus, I would suspect to see the JSON you send look like this:
{
"ImplementationProcessFeelWasSuccessful" : "",
"ImplementationProcessAdviceOtherFederations" : "",
"AdditionalTech" : [...]
}
If it should be a single item being sent, then I'd expect your code to be like this:
function SaveProgress() {
var formData =
{
ImplementationProcessFeelWasSuccessful : $('#wizard #val1').val(),
ImplementationProcessAdviceOtherFederations : $('#wizard #val2').val(),
AdditionalTech : additionaltechs
};
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
However, you are sending an array of items up and that makes no sense here.

Ended up sending the list as a JSON string & receiving it also as a string. In the controller I using the JsonConvert.DeserializeObject method like this:
var additionalTechs = JsonConvert.DeserializeObject<List<AdditionalTechnologyVM>>
(model.AdditionalTech);

Related

Send object to mvc controller using ajax

I am passing multiple parameters in an object and then passing it to a Method in the controller. It is hitting the method but it's not carrying the data to be sent from ajax call to the method . When I am going to check object of the model it displays null. SO can I send the data in such a way or should I try another approach?
Thanks in advance Please help me.
Here is my code.
var Color = [], Material = [], Size = [], FinishingType = [], Style = [];
$('.productFilterLabelList .filterList').on('change', '[type=checkbox]', function () {
debugger;
var Main = {};
var filterType = $(this).parents('.productFilterLabelList').find('.hdn-filter-type').val();
var filterTypeID = $(this).val();
var ischeked = $(this).is(':checked');
if (ischeked) {
if (filterType == 'color') {
Color.push(filterTypeID);
}
else if (filterType == 'size') {
Size.push(filterTypeID);
}
else if (filterType == 'finsih') {
FinishingType.push(filterTypeID);
}
else if (filterType == 'material') {
Material.push(filterTypeID)
}
else {
Style.push(filterTypeID);
}
}
else {
alert('hello');
if (filterType == 'color') {
Color.pop(filterTypeID);
}
else if (filterType == 'size') {
Size.pop(filterTypeID);
}
else if (filterType == 'finsih') {
FinishingType.pop(filterTypeID);
}
else if (filterType == 'material') {
Material.pop(filterTypeID)
}
else {
Style.pop(filterTypeID);
}
}
Main = {
Color: Color,
Size: Size,
FinishingType: FinishingType,
Material: Material,
Style: Style
}
console.log(Main);
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
data: '{Main:' +JSON.stringify(Main)+' }',
success: function (results) {
}
})
});
public ActionResult SearchByAllFilterTags(ProductFilterViewModel Main)
{
return Json("", JsonRequestBehavior.AllowGet);
}`public class ProductFilterViewModel
{
public int[] Color { get; set; }
public int[] Material { get; set; }
public int[] Size { get; set; }
public int[] FinishingType { get; set; }
public int[] Style { get; set; }
public int[] Pattern { get; set; }
//public string FilterText { get; set; }
//public List<ProductFilterViewModel> FilterTextList { get; set; }
}`
You don't need to stringify your object. Just pass your Main object:
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
traditional: true,
data: Main,
success: function (results) {
}
})
Edit:
If your arrays are empty in the action method try to add traditional: true to ajax settings
You do not need to stringify. Use this format:
Main = {
"Color": [{Color}],
"Size": [{Size}],
"FinishingType": [{FinishingType}],
"Material": [{Material}],
"Style": [{Style}]
}
console.log(Main);
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
data: Main,
success: function (results) {
}
})
});
As long as you didn't add quotation marks in your json data, your data will not pass.
This will work if your model at the controller is matched.

The parameters dictionary contains a null entry for parameter (ASP.NET)

I have method to add data to db on Aajax request
Here is code on back-end
public ActionResult AddingInternalAppointment(string Start, string End, string Title, DateTime Date,int id)
{
using (var ctx = new ApplicationDbContext())
{
Appointment appointmentInt = new Appointment()
{
Start_appointment = Start,
End_appointment = End,
Title = Title,
Type_of_appointment = "Internal",
Date = Date
};
ctx.Appointments.Add(appointmentInt);
ctx.SaveChanges();
return Json(new {Result = "Success", Message = "Saved Successfully"});
}
}
And here is AJAX request on front - end:
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
},
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
When I call this function it show me this error, but I have values in Date.
How I can fix this?
Try changing parameter name Date to something else (like appointmentDate). You need to change same in ajax call.
A few things.
Create a model for the Action
public class AppointmentOptions {
public string Start { get; set;}
public string End { get; set;}
public string Title { get; set;}
public DateTime Date { get; set;}
public int Id { get; set;}
}
Update the action accordingly
[HttpPost]
public ActionResult AddingInternalAppointment([FromBody]AppointmentOptions model) {
if(ModelState.IsValid) {
string Start = model.Start;
string End = model.End;
//...
//...code removed for brevity
}
Next on the client update ajax call
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
var model = {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
};
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: JSON.stringify(model), //<-- NOTE
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}

Send Post Data to Controller with Ajax [Project .Net]

I have a project in .Net for school.
I try to send a POST json through ajax a MVC controller 5. I reached the correct function of the controller but it received values are 0 or null:
values in controller are 0 or null
Despite that variables are properly filled the browser console:
variables in browser console
Where does the fault do you think?
Here are some code :
Function that call controller :
function GeneratePDF() {
var dataToSend;
var age = 69;
instruction = "trololololoCOCO";
dataToSend = JSON.stringify({ item: { distance: age, instruction: instruction } });
console.log("dataToSend : " + dataToSend);
var uri = '/GeneratePDF/Print';
$.ajax({
type: 'POST',
url: uri,
data: dataToSend,
contentType: "application/json; charset=utf-8",
})
.done(function (data) {
console.log('pdf controller DONE');
})
.fail(function (jqXHR, textStatus, err) {
console.log(jqXHR);
$("#result").html(jqXHR.responseText);
});
}
Controller :
[HttpPost]
public ActionResult Print(test item)
{
//something
return new Rotativa.ActionAsPdf("ViewPrint",new { id = item }) { FileName = "Cartographie.pdf" };
}
Model :
public class test
{
public int distance;
public string instruction;
public test(int distance, string instruction)
{
this.distance = distance;
this.instruction = instruction;
}
}
Fields are not allowed.
Your model declaration must have get and set properties:
public int distance { get; set; }
public string instruction { get; set; }

Diagnosing JS model binder issue in mvc from ajax

I can't figure out why my action param is coming through null. I'm also not sure of how to even diagnose the issue. I can see the http request data being sent with data and stepping through the debugger shows the object as null, not sure how to see the steps in between.
Models
public class ComplexObj
{
public int Id { get; set; }
public int Test1 { get; set; }
public decimal Test2 { get; set; }
}
public class BiggerObj
{
public BiggerObj()
{
ComplexObj = new List<ComplexObj>();
}
public long OtherId { get; set; }
public string Name { get; set; }
public ICollection<ComplexObj> ComplexObjs { get; set; }
}
Action
[HttpPost]
public void TestAction(BiggerObj[] biggerObjs)
{
...// biggerObjs is null :(
}
View
function ajaxCall() {
var data = [];
var bigObj = new Object();
bigObj.OtherId = 123;
bigObj.Name = "TestName";
bigObj.ComplexObj = [];
var complexObj = new Object();
complexObj.Id = 789;
complexObj.Test1 = 123;
complexObj.Test2 = 456;
bigObj.ComplexObj.push(complexObj);
data.push(bigObj);
}
}
$.ajax({
url: SITEROOT + "myController/TestAction",
cache: false,
type: 'POST',
data: data,
complete: function() {
alert('done');
}
});
}
Solved
You must use:
JSON.stringify and declare the contentType as "application/json; charset=utf-8"
Parse the decimal value by using parseFloat() function, decimal is considered as int by default binder.
Change your Action to this:
[HttpPost]
public ActionResult TestAction(BiggerObj[] biggerObjs)
{
...// biggerObjs is null :(
}
Change your ajaxCall function to this:
//ajaxCall
function ajaxCall() {
var data = [];
var bigObj = {
OtherId : 123,
Name : "TestName",
ComplexObjs : new Array()
};
var ComplexObjs = {
Id: 789,
Test1: 123,
Test2: parseFloat(456)
// decimal types are considered an integer, you have to parse
};
bigObj.ComplexObjs.push(ComplexObjs);
data.push(bigObj);
$.ajax({
url:"/Test/TestAction",
cache: false,
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
complete: function () {
alert('done');
}
});
}
I tested, works fine.

ASP.NET Web Service JSON Arrays

I need some help with my web service and json call.. stuck trying to get the data returned, I've done this successful with strings and objects.. but not an array...
My Web Service Contains:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSearchCriteria()
{
var js = new JavaScriptSerializer();
var obj = HttpContext.Current.Session["mysessionname"];
if (obj == null)
{
var result = new Criteria[]
{
new Criteria() { Key = Guid.NewGuid(), Operator = "=", ColumnName = "CheckID", Value = "" }
};
var serial = js.Serialize(result);
return serial;
}
else
{
var serial = js.Serialize((Criteria[])obj);
return serial;
}
}
Criteria is:
[Serializable]
public class Criteria
{
public Guid Key { get; set; }
public string ColumnName { get; set; }
public string Operator { get; set; }
public string Value { get; set; }
}
My Page Contains:
<script type="text/javascript">
function RefreshCriteria() {
$.ajax({
type: 'POST',
url: '<%= System.Web.VirtualPathUtility.ToAbsolute("~/Services/WebService.asmx/GetSearchCriteria") %>',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
success: function (data) {
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
}
});
}
$(document).ready(function () {
RefreshCriteria();
});
</script>
What I'm getting is undefined every time.. tried doing
$(data).each(function (i) {
var obj = data[i];
alert(obj);
});
$(data).each(function (i, obj) {
alert(obj);
});
$(data).each(function (i) {
alert(this);
});
None worked so far..
you can tighten up the ajax
$.ajax({
type: 'POST',
url: '*you need a url here*',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
console.log(item);
});
}
});
next using either firebug or fiddler monitor the request/response to ensure what you are sending and receiving is what you expected.

Categories

Resources