I have a game object in client side JavaScript that looks like this right before being sent to the server:
Here it is server side a second later, note all the properties are filled, and the Questions list is populated with the correct number of question, however the properties of each question are null, whereas on the client side they had the correct values.
Here is the code for the models:
public class Game
{
public Game()
{
Questions = new List<Question>(5);
}
public int GameID { get; set; }
public Guid UserID { get; set; }
public Guid CurrentGameID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<Question> Questions { get; set; }
}
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public IEnumerable<int> Answers { get; set; }
public int SelectedAnswer { get; set; }
}
And here is how I send the object back to the server:
// Send completed game back to server
$.post("Games/CompleteGame", currentGame, function (results)
{
// display results to user
}
Based on Ek0nomik's comment asking about the content-type, I rewrote my ajax call to set contentType to json:
$.ajax(
{
url: "Games/CompleteGame",
type: "POST",
data: JSON.stringify(currentGame),
contentType: "application/json",
success: function (results)
{
// show results to user...
}
As it turns out, this was all it needed to make it work.
Related
Im trying to pass an Id and object of picList to the controller and it shows up null. I've looked at all the other SO solutions and changed my code to what they said and Im still getting null for both values in the controller.
So I've even tried to change the data that is being sent to the controller as such to see if that made any difference and it didn't.
in ajax call i changed the data to such
data: {"Name": "Adam"},
and added this to the controller and still nothing is getting passed.
UnitImages(string Name,..
here is what the JSON.stringify(data) looks like.
View Model
public class FileViewModel
{
public FileViewModel()
{
UnitPicturesList = new List<UnitPictures>();
}
public IList<IFormFile> Files { get; set; }
[Required]
public int AuctionId { get; set; }
public string FileLocation { get; set; }
public List<UnitPictures> UnitPicturesList { get; set; }
}
model
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
controller
[HttpPost]
public ActionResult UnitImages(long auctionId, List<UnitPictures> picList)
{ ...
}
Ajax call
function UpdateImages(auctionId, picList) {
var data = { auctionId: auctionId, picList: picList };
console.log(JSON.stringify(data));
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: '/PhotoUploader/UnitImages',
data: JSON.stringify(data),
success: function(data){
if(data.Result == 1) {
alert("images where successfully updated.");
}else {
alert('images where successfully updated.');
}
},
error: function() {
alert("The images were not updated because of a problem.")
}
});
}
Asp.net core MVC default binding value from form, Here you can try to add [FromBody] attribute on your parameter to change the resource to bind value from body.
[HttpPost]
public ActionResult UnitImages([FromBody]string Name)
{ ...
}
Model details you can refer to Model Binding.
Try using a class that match the posted model. Something like this:
public class UnitPictures_ViewModel
{
public int AuctionId {get;set;}
public List<UnitPictures> PicList { get; set; }
}
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
I generate the js object, which looks as follows:
cartStorage = {
name: 'testcustomer',
email: 'test#gmail.com',
items: [
{
licenseName: 'Private',
licensePrice: 2
},
{
licenseName: 'Public',
licensePrice: 4
}
],
totalPrice: 6
}
Then I pass this object to mvc controller using ajax
$.ajax({
url: '/TestPayment/ChargeTest',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(cartStorage),
success: function(response){
if (response != null) {
alert(response);
} else {
alert("Something went wrong");
}
}
});
Here's the viewmodel associated with this method
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public Items Items { get; set; }
}
}
Here's the mvc controller method, which processes the ajax request
[HttpPost]
public ContentResult ChargeTest([FromBody] PayerInfo model)
{
String FullName = model.name;
}
But when the server executes the controller method, the model turns out to be null.
However, if I comment out the Items class and the instance creation in the PayerInfo class in the viewmodel, then the model is being forwarded successfully and all the data is stored, I'm just having the problem with the list inside of js object.
What am I doing wrong?
items in your json object is a list. So you need to change the type of Items in your c# model to a list.
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public List<Items> Items { get; set; }
}
}
I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error
Error
Controller
[HttpPost]
public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
{
//want to get json of "questionlist" which is send from javascript like
var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);
}
Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here
Javascript
var data = new FormData();
var QuestionnaireList = [];
QuestionnaireList.push({
FieldID: $(this).attr("data-fieldid"),
attributeID: $(this).attr("data-attributeid"),
attributeValue: $(this).val(),
websitesID: 2,
OrderID: $('#orderid').val(),
orderbitID: $('#orderbidid').val(),
serviceId: $(this).attr("data-serviceid"),
subServiceId: $(this).attr("data-subserviceid"),
IsSubmit: IsSubmit,
});
data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
type: "POST",
url: path,
contentType: 'application/json',//"application/json; charset=utf-8",
processData: false,
dataType: "json",
data: data,
success: function (result) {
if (result.sucess == "save") {
alert('Your form has been saved.');
}
else if (result.sucess == "Submit") {
alert('Your form has been submitted.');
window.location.href = result.Url;
}
},
error: function (result) {
alert('Oh no ');
}
});
Here is a model class AttributeValueTB
Class
public class AttributeValueTB
{
public long attributeValueID { get; set; }
[Required]
[StringLength(200)]
public string attributeValueCode { get; set; }
public int FieldID { get; set; }
public int attributeID { get; set; }
public string attributeValue { get; set; }
public int websitesID { get; set; }
public long OrderID { get; set; }
public long orderbitID { get; set; }
public long serviceId { get; set; }
public long subServiceId { get; set; }
public string extra1 { get; set; }
public string extra2 { get; set; }
[StringLength(200)]
public string attributeCode { get; set; }
public bool isActive { get; set; }
public bool isShow { get; set; }
public bool IsSubmit { get; set; }
[Column(TypeName = "date")]
public DateTime? createDate { get; set; }
[Column(TypeName = "date")]
public DateTime? modifiedDate { get; set; }
public int? createBy { get; set; }
public int? modifiedBy { get; set; }
[Column(TypeName = "timestamp")]
[MaxLength(8)]
[Timestamp]
public byte[] Timestamp { get; set; }
}
You don't need to serialize anything manually, as long as you've provided a model class in C#.
Json.NET is quite smart and serializes your parameters automagically.
[HttpPost]
public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
{
// Form is serialized and can be used here
}
If you'd like to read the cookies too, you could use Request.Cookies in this method.
you need to collect information from 'jsoncontent' not from 'form'
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
and if you using class object as parameter also work with your context, need to change the method as put like this.
[HttpPut]
public HttpResponseMessage Put(int id)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
...
}
In my MVC 5 Web API application, i have a method with signature
public HttpResponseMessage PostDefects(int user, string order, string mode, [FromBody]List<Defect> defects)
This API method is called from jQuery as following
$.ajax({
type: "POST",
url: "api/postdefects/123/456/myMode",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(priv.DefectList),
success: function () {
alert('REST call OK');
},
error: function() {
alert('REST call not OK')
},
cache: false
});
On 5 computers this is working without any problem, except 2 computers. For 1 of these computers, the issue got auto-solved without doing anything from my side... On the other one I still have the issue left, and I don't get it solved there.
When I am calling this API from my html page, I receive a 200 (OK) response, but my json body JSON.stringify(priv.DefectList) is not received in the API method. When checking in Fiddler afterwards, I can clearly see that the POST method is receiving the 200 (OK) response, and that the body was sent to the API method. Inside my API method however, I don't receive the object.
My web browser is Google Chrome 42.0.2311.135 m.
Any help would be great!
This is my Defect class
public partial class Defect
{
public int ID { get; set; }
public string order { get; set; }
public string operation { get; set; }
public string part_nbr { get; set; }
public string tool { get; set; }
public string imgName { get; set; }
public Nullable<int> imgWidth { get; set; }
public Nullable<int> imgHeight { get; set; }
public double xPos { get; set; }
public double yPos { get; set; }
public int reason { get; set; }
public string reasonText { get; set; }
public Nullable<System.DateTime> isRepaired { get; set; }
public Nullable<System.DateTime> createdTS { get; set; }
public string severity { get; set; }
public string mode { get; set; }
public string badge_nbr { get; set; }
}
And this is an example of the data that is passed
[
{
"order":"F00000021489",
"operation":"0010",
"part_nbr":"1741845",
"reason":"6",
"reasonText":"RWK06 Vosk - poškodenie",
"xPos":417,
"yPos":390,
"imgWidth":880,
"imgHeight":824,
"imgName":"1741845_A.png",
"createdTS":"2015-05-07T08:12:12.109Z",
"tool":"1741845T05",
"mode":"REWORK",
"badge_nbr":"0180371"
}
]
Not sure if it's just the time of day, lack of coffee or over indulgence of sugar from last night. Besides that I'm trying to get this working. I do not want to change / modify / add a new web service method.
I have an asmx web service:
public UserLogin Login(UserLogin p_objUserLogin)
{
}
I need to hook a JQuery ajax call up to that. The UserLogin object is not that complex:
public class UserLogin
{
public UserLogin();
public string Privileges { get; set; }
public string ClientCodeID { get; set; }
public UserDetails User { get; set; }
public string UserLoginMessage { get; set; }
public bool Valid { get; set; }
}
The UserDetails object is quite large, and includes a lot more data. (Hopefully I don't need to build the entire object tree to get this to work).
public class UserDetails
{
public string CellPhone { get; set; }
public string Email { get; set; }
public string EncryptedPassword { get; set; }
public string FirstName { get; set; }
public string FullName { get; }
public string Initials { get; set;
public bool InService { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public byte[] Signature { get; set; }
public string SimCard { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public SecurityRole UserSecurityRole { get; set; }
public Workgroup UserWorkgroup { get; set; }
}
The script I'm playing around with:
function CallService() {
var p_objUserLogin = {};
p_objUserLogin['ClientCodeID'] = "Test";
var DTO = { 'p_objUserLogin': p_objUserLogin };
$.ajax({
type: "POST",
url: "UtilityServices2006.asmx/Login",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + ", " + status + ", " + error);
},
complete: function (req, status) {
alert(req + ", " + status);
}
});
}
Any help would be quite amazing.
Ensure your webservice class and method are decorated to handle incoming ajax/json requests:
[ScriptService]
public class MyService: WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public UserLogin Login(UserLogin p_objUserLogin)
{
}
}
I'm not familiar with the notation you're using to configure your payload object (p_objUserLogin['ClientCodeID'] = "Test";). I've usually used slightly different notation:
p_objUserLogin.ClientCodeID = 'Test';
However, that might be a red herring - I'm not a JS-objects expert, so your notation may be perfectly valid.
Finally, I'm not sure if JS will automatically convert your object to JSON (var DTO = { 'p_objUserLogin': p_objUserLogin };). I use the json2 library to explicitly serialize JS objects to JSON:
var DTO = { 'p_objUserLogin': JSON.stringify(p_objUserLogin) };
Hope this helps you nail down the issue.