Constant 400 response, sending complex javascript object to MVC controller - javascript

Yet again another MVC issue. One day I'll look at my "MVC learning days" and smile.
So to the point and exactly as the title indicates; A constant 400 response, I've read numerous posts on SO and still cannot seem to get my logic working. If I may show you the logic, someone maybe able to help me.
Controller:
public JsonResult CreateExtendedProperty(ExtendedPropertyDefinitionViewModel extendedPropertyDefinitionViewModel)
{
//I originally had JsonResult as ActionResult, still no change.
var p = extendedPropertyDefinitionViewModel;
//Temp
//return Json(new { Success = false, ErrorMessage = "Error creating property" });
}
The Ajax/Javascript:
var extendedPropertyDefinition = JSON.stringify({
DefinitionId: '0',
Title: propertyInfo["Title"],
OrganisationId: '0',
Organisation: '',
TypeId: propertyInfo["TypeId"],
SortOrder: 0,
IsEnumerated: propertyInfo["IsEnumerated"],
AllowMultiSelect: propertyInfo["AllowMultiSelect"],
IsDate: propertyInfo["IsDate"],
LastUpdatedBy: "",
LastUpdatedDateTime: new Date().toISOString(),
CreatedBy: "",
CreatedByDateTime: new Date().toISOString(),
Options: {
OptionId: '0',
Option: '',
OptionValue: '',
SortOrder: 0,
LastUpdatedBy: '',
LastUpdatedDateTime: new Date().toISOString(),
CreatedBy: '',
CreatedByDateTime: new Date().toISOString(),
}
});
$.ajax({
url: "<%= Url.Action('CreateExtendedProperty', 'Organisation') %>",
contentType: "application/json; charset=utf-8",
dataType: "json",
//traditional: true,
type: 'POST',
data: extendedPropertyDefinition,
success: function(e) {
alert('success');
//Rebuild Grid?
},
error: function(e) {
alert('request failed (500)');
}
});
The payload:
Hopefully someone can put on the right path, all will be much appreciated.
Regards,

So to just get the answer from comments - you have to ensure that <%= Url.Action('CreateExtendedProperty', 'Organisation') %> gets compiled. If it is in a separate JS file you have to pass it from your view. Otherwise it could be some other problem(if you are using Razor syntax, it should something like #Url.Action("CreateExtendedProperty", "Organisation"))

Related

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

AJAX send null on my VW in controller

Good evening SO, this been bugging me for a few hours already and still haven't figure out how to fix this.
All of my request data is fine except for subscriptionTag, it's value is always null whenever i send the request to server. I even tried removing JSON.stringify but it gives me false value instead.
Edit : Added HTTPPost in controller and type: post in javascript, i'm having an 500(internal server error) now :(
Edit 2 : Added Request Payload and Request URL
Request URL: http://localhost:49895/exclusive/send
Request Payload:
subscriptionTag=%7B%22IsAutomotive%22%3Atrue%2C%22IsMusicandDance%22%3Afalse%2C%22IsBeautyLifestyle%22%3Atrue%2C%22IsNighlifeEvent%22%3Afalse%2C%22IsFashion%22%3Afalse%2C%22IsRestaurantBar%22%3Afalse%2C%22IsHealthAndFitness%22%3Afalse%2C%22IsSportsOutdoor%22%3Afalse%2C%22IsHomeDecor%22%3Afalse%2C%22IsTravel%22%3Afalse%7D&pageid=33&emailAddress=gabyap1390%40gmail.com&token=cz0xJmV4Y2x1c2l2ZUlkPTM20&FirstName=Gabriel&source=%2Fsiggpay&MembershipLevelId=33
.NET
`
[HttpPost]
[Route("~/exclusive/send")]
public JsonResult Send(SubscriptionTag subscriptionTag, int pageid, string EmailAddress, string token, string FirstName = "", string source = "", int? MembershipLevelId = null)
{
return Json(new { error = false }, JsonRequestBehavior.AllowGet);
}
`
JAVASCRIPT
var subscriptionTag = {};
subscriptionTag.IsAutomotive = $('#IsAutomotive').is(":checked");
subscriptionTag.IsMusicandDance = $('#IsMusicandDance').is(":checked");
subscriptionTag.IsBeautyLifestyle = $('#IsBeautyLifestyle').is(":checked");
subscriptionTag.IsNighlifeEvent = $('#IsNighlifeEvent').is(":checked");
subscriptionTag.IsFashion = $('#IsFashion').is(":checked");
subscriptionTag.IsRestaurantBar = $('#IsRestaurantBar').is(":checked");
subscriptionTag.IsHealthAndFitness = $('#IsHealthAndFitness').is(":checked");
subscriptionTag.IsSportsOutdoor = $('#IsSportsOutdoor').is(":checked");
subscriptionTag.IsHomeDecor = $('#IsHomeDecor').is(":checked");
subscriptionTag.IsTravel = $('#IsTravel').is(":checked");
$.ajax({
url: MyAppUrlSettings.MyUsefulUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: {
subscriptionTag: JSON.stringify(subscriptionTag),
pageid: pageid,
emailAddress: emailAddress,
token: token,
FirstName: firstName,
source: source,
MembershipLevelId: membershipLevelId
},
success: function (result) {
if (result.error == false)
location.href = ""
}
});
},`
Just in case you might ask, heres my query string parameters.
subscriptionTag: {"IsAutomotive":false,"IsMusicandDance":false,"IsBeautyLifestyle":true,"IsNighlifeEvent":true,"IsFashion":false,"IsRestaurantBar":true,"IsHealthAndFitness":true,"IsSportsOutdoor":false,"IsHomeDecor":false,"IsTravel":false}
pageid: 33
emailAddress: gabyap1390#gmail.com
token: cz0xJmV4Y2x1c2l2ZUlkPTM20
FirstName: Gabriel
source: /siggpay
MembershipLevelId: 33
Thanks to all who commented on this but I managed to fix my problem I change my data from
data: {
subscriptionTag: JSON.stringify(subscriptionTag),
<code>some code here</code>
},
into
data: JSON.stringify({
subscriptionTag: subscriptionTag,
<code>some code here</code>
}),

Cant send Object with property that has array of objects

I'm trying to send an object that looks like this
var postBody = {
id: userID,
objectID: [0, 1],
objects: [
{id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0.30864197530864196},
{id: 1, x: 0.5277777777777778, y: 0.08453888888888889, width: 0.0823045267489712, height: 0.30864197530864196}
]
};
this is ajax call
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'JSONP',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
this is what it looks like on server
{ id: '583f137fc338b517ec467643',
'objectID[]': [ '0', '1' ],
'objects[0][id]': '0',
'objects[0][x]': '0.33930041152263374',
'objects[0][y]': '0.08145246913580247',
'objects[0][width]': '0.0823045267489712',
'objects[0][height]': '0.30864197530864196',
'objects[1][id]': '1',
'objects[1][x]': '0.5277777777777778',
'objects[1][y]': '0.08453888888888889',
'objects[1][width]': '0.0823045267489712',
'objects[1][height]': '0.30864197530864196' }
if I put data: JSON.stringify(postBody) this is what I get
{ '{"id":"583f137fc338b517ec467643","objectID":[0,1],"objects":[{"id":0,"x":0.5,"y":0.5,"width":0.1,"height":0.1},{"id":1,"x":0.5401234567901234,"y":0.1833043209876543,"width":0.0823045267489712,"height":0.30864197530864196}]}': '' }
And it works! but then I cannot JSON.parse() it
this is what I get when I try
TypeError: Cannot convert object to primitive value
and all that Im doing on data on backend is this
console.log(JSON.parse(req.body)); // in the first example it was the same thing but only without JSON.parse()
Anyone have an idea why this is happening here?
Even if you have a suggestion on what I could try feel free to post here, otherwise I'm gonna have to write a function for parsing these badass inputs lol.
All the parsing/stringifying is handled by Node, so don't worry about it, just pass your object as it is, and you'll be able to access its properties in req.body.
client :
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
server :
console.log(req.body); //should give you [Object object]
you can then send it right back with: res.status(200).json(req.body));
and read it in your ajax callback :
success: function(data) {
console.log(data);
},

Jasper Async Report - Empty, why?

Lets start , firstly I get parameters for specific report for exmaple
var config = {
url : "http://exmaple.com/jasperserver/rest_v2/reports/reportFolder/exampleReport/inputControls",
method: "GET",
headers: {
Accept: "application/json;"
},
}
Everything is ok, I get a response with an array of inputs,
The array contains, 2 objects with :
First:
{
description: "Date_from",
id: "Date_from",
label: "Date from",
type: "singleValueDate"
}
Second:
{
description: "Date_to",
id: "Date_to",
label: "Date_to",
type: "singleValueDate"
}
Both inputs have a property:
validationRules[0].dateTimeFormatValidationRule.format = "yyyy-MM-dd"
So now I want to run a async report (I will pass async parameter false for now, se there is less code here)
var params ={
reportUnitUri: "/reportFolder/exampleReport",
outputFormat: "html",
freshData : true,
saveDataSnapshot : false,
ignorePagination: true,
async : false,
interactive: false,
allowInlineScripts: true,
parameters: {
"Date_from":["2014-08-01"],
"Date_to":["2015-10-08"]
}
}
So now I try to generate async report:
var config = {
url : "http://exmaple.com/jasperserver/rest_v2/reportExecutions",
headers: {
Accept: "application/json"
},
data: params,
method: "POST"
}
I get a success response, but
totalPages: 0,
requestId: "0200cf28-300f-4e76-b99e-e479be4980ba",
reportURI: "/reportFolder/exampleReport/",
status: "ready",
exports[0].id: "c9a5578a-6bc8-4c3e-8a78-9056ef19f456",
exports[0].status: "ready",
exports[0].outputResource :{
contentType: "text/html",
outputFinal: true
}
When I try to get the output of the report by calling :
http://exmaple.com/jasperserver/rest_v2/reportExecutions/0200cf28-300f-4e76-b99e-e479be4980ba/exports/c9a5578a-6bc8-4c3e-8a78-9056ef19f456/outputResource
The report is empty.
Runing the same via :
http://exmaple.com/jasperserver/rest_v2/reports/reportFolder/exampleReport.html?Date_from=2014-08-01&Date_to=2015-09-08
Gives me a filled report,
Can anyone point me what I'm doing wrong ? :/
I'm pretty sure that it may be something wrong with the parameters but I tried in various ways and I can't find a solution by myself :/
The thing was that the parameters passed to the async report were badly formatted, it should be like this:
parameters: {
reportParameter: [
{name : "Date_from",value : ["2014-08-01"]},
{name : "Date_to",value : ["2015-10-08"]}
]
}

Webmethod not firing in FlexiGrid

I'm using FlexiGid for my project.But the problem is WebMethod not firing.(Json/Ajax call)
I have put a Debug point to the Webmethod but it's not firing and also Firebug shows the web method Url is correct.
Here i have put the code
Ajax Call
function flexgrid() {
debugger;
$("#flex1").flexigrid({
url: '/WebMethods.aspx/GetIssueSummaryById',
dataType: 'json',
contentType: "application/json; charset=utf-8",
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
],
data: JSON.stringify({ ProjectId: "1", UserId: "1" }), //Hard code this values at this time
buttons : [
{ name: 'Add', bclass: 'add', onpress: test },
{ name: 'Delete', bclass: 'delete', onpress: test },
{separator: true},
{name: 'A', onpress: sortAlpha},
{name: 'B', onpress: sortAlpha}
],
searchitems : [
{ display: 'Project', name: 'project' },
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "id",
sortorder: "asc",
usepager: true,
title: 'Issue Summary',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 1000,
height: 500
});
};
Web Method( thats in WebMethods.aspx file )
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<IssuesVM> GetIssueSummaryById(string UserId, string ProjectId)
{
//Guid LoggedInUserId = new Guid(UserId);
//int ProjectId = Convert.ToInt32(ProjectId);
List<IssuesVM> lst = new List<IssuesVM>();
try
{
SqlCommand comIssueSummary = new SqlCommand("SP_GetIssuesByProjectIDAndOwnerId", conn);
comIssueSummary.CommandType = CommandType.StoredProcedure;
//comIssueSummary.Parameters.Add("#ProjectId", SqlDbType.Int).Value = ProjectId;
// comIssueSummary.Parameters.Add("#UserId", SqlDbType.UniqueIdentifier).Value = LoggedInUserId;
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataReader rdr = comIssueSummary.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
//Some code goes here
}
}
catch (Exception)
{
throw;
}
return lst;
}
After that Firebug shows this
Image Here
Can anyone know the Error for this ? Not firing webmethod ?
P.S - I saw some solution in below post[Click Here], I did thatone to the flexigrid.js file but it also not working.
Here is the Change
FlexiGrid.js file (before change )
$.ajax({
type: p.method,
url: p.url,
data: param,
dataType: p.dataType,
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
FlexiGrid.js (After Change )
$.ajax({
contentType: "application/json; charset=utf-8",
data: "{}", // to pass the parameters to WebMethod see below
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
So first off, it might be a good idea to move this to a WebService.asmx file. It is just best and common practice to do so. .ASPX pages respond with HTML/CSS/Javascript normally and .asmx responds with JSON or XML.
Either way, whether the Ajax calls for flexigrid are to a WebService or a Web Forms page, when you add the attribute [WebMethod] to expose a method doing the first Ajax call can be a bit challenging. There is something a bit finicky about Ajax calls to public WebMethods. The finicky arises around the content-type of the request and if the request is JSON or XML and if the response is JSON or XML.
So I am going to show you what I know works for a project I used Flexigrid:
$('#gridTablegSearchProperty').flexigrid({
url: 'Services/WSgSearch.asmx/gridTablegSearchProperty',
colModel: [...
You will notice in the first code snippet I do not set the contentType or the dataType properties of Flexigrid.
And now my WebMethod signature
[WebMethod]
public XmlDocument gridTablegSearchProperty()
{
System.Collections.Specialized.NameValueCollection nvc = HttpContext.Current.Request.Form;
int pgNum = nvc.GetValueAsInteger("page").GetValueOrDefault(1);
int pgSize = nvc.GetValueAsInteger("rp").GetValueOrDefault(20);
string sortName = nvc.GetValueOrDefaultAsString("sortname", "key");
string sortOrder = nvc.GetValueOrDefaultAsString("sortorder", "desc");
string query = nvc.GetValueOrDefaultAsString("query", string.Empty);
string qtype = nvc.GetValueOrDefaultAsString("qtype", string.Empty);
My WebMethod is in a .asmx file, it will not matter if you keep yours in a code behind file but I would move to a WebService and drop the WebMethods.aspx this is poor naming convention and file use convention.

Categories

Resources