dont Post JSON array to mvc controller - json

I'm trying to post JSON to a mvc controller through AJAX. I use this code but it does not do the post.
$(document).ready(function(){
$(".btn-success").click(function(e){
var urData = { City: 'Moscow', Age: 25 };
$.ajax({
url: "/Category/Create/",
type: "POST",
dataType: "json",
traditional: true,
contentType : "application/json",
data: urData,
success: function(maindta) {
alert(maindta);
},
error: function(jqXHR, textStatus){
}
});
e.preventDefault(); //STOP default action
});
});
This is controller action
[HttpPost]
public virtual JsonResult Create(List<object> urData){
}

Your posting back an object with 2 properties so you need a model with those 2 properties
public class MyModel
{
public string City { get; set; }
public int Age { get; set; }
}
and the method needs to be changed to
public JsonResult Create(MyModel model)
{
.... // model will be populated with the values you sent
return Json(...);`
}
and you need to remove the following options from the ajax method
contentType : "application/json",
traditional: true,
Alternatively, you method can be
public JsonResult Create(string city, int age)
but you lose the benefits of model validation
Side note: Always use the Url.Action() method to ensure your url's are correctly generated
url: '#Url.Action("Create", "Category")',

Related

MVC Date parameter always null using AJAX (JSONConvert Serialize)

Currently working on the passing of view data to controller for MVC via AJAX post request
I noticed that date parameter is always null/default(01/01/0001) when I received it in my controller , I don't know the reason. Can someone shed a light?
My AJAX request is tihs
var details = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ param: details }),
url: "#Url.Action("Index", "PaymentPlan")",
success: function (result) {
$("#divPayPlan").html(result);
},
error: function (error) {
console.log(error.responseText);
}
});
My Model is:
public class PayPlan{
public virtual int MaxTerms { get; set; }
[DataType(DataType.Date)]
[JsonProperty]
[JsonConverter(typeof(IsoDateTimeConverter))]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime FirstPaymentDate { get; set; }}
See this Image JSON Serialze
See my UI UI

Invalid JSON Primitive When Passing With Ajax

I'm trying to create a json object and pass it as a parameter using Ajax. Here's the js
var model = {
"Name": "test",
"Location": "Place",
"Interests": ["Code", "Coffee"]
};
$.ajax({
type: "POST",
url: "/CT01211/test",
contentType: "application/json'",
dataType: "json",
data: {
message: model
}
});
Here's the c#:
public class ModelTest
{
public string Name { set; get; }
public string Location { set; get; }
System.Collections.Generic.List<string> Interests { set; get; }
}
[HttpPost]
public ActionResult test (ModelTest message)
{
return Json(message);
}
Everything time I try I get the error: "Invalid JSON primitive".
I've tried JSON.stringify(model)
I've tried single quotes instead of double when building the model variable
I've tried changing the contentType and dataType
I've tried not having quotes around the properties:
var model = {
Name: "test",
Location: "Place",
Interests: ["Code", "Coffee"]
};
No matter what, I get the error.
Little help?

POSTing complex JSON to ASP.NET Core Controller

I have the following models in my ASP.NET Core code:
public class TestItem
{
public string Id { get; set; }
public string Name { get; set; }
public List<TestSubItem> SubItems { get; set; }
}
public class TestSubItem
{
public string Id { get; set; }
}
and the following method in my Controllers/TestController.cs:
// POST: Test/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([FromBody]TestItem item)
{
// Use item here...
return View(item);
}
I have the following JavaScript in my page:
var mySubItems = [{"Id": "1"}];
function submitForm() {
// myForm contains an Id textbox and a Name textbox
$("#myForm").submit();
};
function doPost() {
var testItem = {
Id: "2",
Name: "testName",
SubItems: mySubItems
};
$.ajax({
url: '#Url.Action("Create" ,"Test")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(testItem),
success: function (data) {
alert(data);
},
error: function (error) {
var x = error; //break here for debugging.
}
});
};
When I use doPost, I always get 400 Bad Request back from the server. submitForm on the other hand works fine, but I don't know how to include mySubItems in the data sent to the server.
What's the quickest way out of this?
Including [ValidateAntiForgeryToken] on your controller is causing the problem. You need to include the token when you post the data. MVC automatically includes it the form which is why submitForm() works.
The challenge is that I do not know how to make it work with JSON data getting posted. You might be able to by adding the following into testItem:
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]', form).val()
For more information, check out include antiforgerytoken in ajax post ASP.NET MVC

In Mvc,I cant getting values from JSON object

I cant any value from json.Values come 'null'.Where is the problem?
MY:JQUERY CODE IN siparis.cshtml
var array_table = [];
array_table.push({
arrayName: "Name Value",
arrayMail: "Mail Value",
arrayMobile: "mobile Value"
});
}
$.ajax({
url: '#Url.Action("SiparisOlustur")', type: "POST", dataType: "json",
data: JSON.stringify( array_table),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#POCStatus').html('<div class="success">POC Removed Successfully.</div>');
},
error: function () {
$('#POCStatus').html('<div class="field-validation-error">Some Error Occured in Removing POC.</div>');
}
});
My JSON Model:
public class JsonModel
{
public string arrayName { get; set; }
public string arrayMail { get; set; }
public string arrayMobile { get; set; }
}
My SiparisController:
[HttpPost]
public ActionResult SiparisOlustur(List<JsonModel> array_table)
{
return View();
}
Result is this:
ARRAY_TABLE IS COMING NULL
Thank You,
Regards,
B.Y.
Give array_table name in data in ajax call as :
data: {array_table : JSON.stringify( array_table)}

knockout with mapping plugin, posting using postJSON with MVC, model collections always contain null objects

I've got a model for my Page Creation:
public class PageCreateModel : ActionModel
{
public IList<KeyValuePair<Guid, string>> AvailablePermissions { get; set; }
public IList<KeyValuePair<Guid, string>> AvailableUsers { get; set; }
public IList<KeyValuePair<Guid, string>> AvailableGroups { get; set; }
public string Heading { get; set; }
public bool ShowHeading { get; set; }
public string Description { get; set; }
public ICollection<string> RouteUrls { get; set; }
public IList<KeyValuePair<Guid, string>> SelectedEditingPermissions { get; set; }
public IList<KeyValuePair<Guid, string>> SelectedEditingUsers { get; set; }
public IList<KeyValuePair<Guid, string>> SelectedEditingGroups { get; set; }
}
And I am using knockout mapping to convert this into a knockout model on page load:
var mappedModel = ko.mapping.fromJS(#Html.Raw(JsonConvert.SerializeObject(Model)));
Upon posting and using this code:
mappedModel.save = function(form) {
mappedModel.AvailablePermissions([]);
mappedModel.AvailableUsers([]);
mappedModel.AvailableGroups([]);
console.log(ko.toJS(mappedModel));
ko.utils.postJson('#Url.Action("Create", "Page")', { pageCreateModel: ko.toJS(mappedModel) });
};
It goes to this Action:
[HttpPost]
public ActionResult Create(PageCreateModel pageCreateModel)
{
return View(HydrateModel(pageCreateModel));
}
At this point my standard property values get posted find. But my collections (so far on my page I've only added SelectedEditingUsers) have empty objects in the collection. For instance if on the page I add 2 users to the collection, and I post it. The MVC model's SelectedEditingUsers will have a collection of two, but those objects contain an Empty Guid and null for the value.
Here is the data being sent to the server from Chrome console:
pageCreateModel:{"AvailablePermissions":[],"AvailableUsers":[],"AvailableGroups":[],"Heading":"Test","ShowHeading":true,"Description":null,"RouteUrls":null,"SelectedEditingPermissions":[],"SelectedEditingUsers":[{"Key":"d81f409a-5fed-4330-8640-004bede4e6fb","Value":"User1"},{"Key":"5628ad64-567b-499d-bee1-cb6c3dc397eb","Value":"User2"}],"SelectedEditingGroups":[],"ActionSuccess":false,"ActionMessage":null,"ko_mapping":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{"AvailablePermissions[0].Key":true,"AvailablePermissions[0].Value":true,"AvailablePermissions1.Key":true,"AvailablePermissions1.Value":true,"AvailablePermissions[2].Key":true,"AvailablePermissions[2].Value":true,"AvailablePermissions[3].Key":true,"AvailablePermissions[3].Value":true,"AvailablePermissions[4]...[etc]
How can I fix it so that the full model gets properly received by MVC? I need to use postJSON so I can use RedirectToAction and other similar things.
EDIT: Trying the AJAX call instead:
mappedModel.save = function(form) {
mappedModel.AvailablePermissions([]);
mappedModel.AvailableUsers([]);
mappedModel.AvailableGroups([]);
//mappedModel.__ko_mapping__([]);
//console.log(ko.toJS(mappedModel));
$.ajax({
url: '#Url.Action("Create", "Page")',
type: 'POST',
data: ko.toJSON(mappedModel),
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert("Success!");
}
});
//ko.utils.postJson('#Url.Action("Create", "Page")', { pageCreateModel: ko.toJS(mappedModel) });
//ko.utils.postJson($("form")[0], { pageCreateModel: ko.toJS(mappedModel) });
//ko.utils.postJson('#Url.Action("Test", "Page")', { ko.toJS(mappedModel) });
};
And I still get the same problem:
And here is the POST from that:
{"AvailablePermissions":[],"AvailableUsers":[],"AvailableGroups":[],"Heading":"Test","ShowHeading":true,"Description":null,"RouteUrls":null,"SelectedEditingPermissions":[],"SelectedEditingUsers":[{"Key":"5628ad64-567b-499d-bee1-cb6c3dc397eb","Value":"User1"},{"Key":"6d7439aa-7728-4add-953f-28b306fff5d0","Value":"User2"}],"SelectedEditingGroups":[],"SelectedViewingPermissions":[],"SelectedViewingUsers":[],"SelectedViewingGroups":[],"ActionSuccess":false,"ActionMessage":null,"ko_mapping":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{"AvailablePermissions[0].Key":true,"AvailablePermissions[0].Value":true,"AvailablePermissions1.Key":true,"AvailablePermissions1.Value":true,"AvailablePermissions[2].Key":true,"AvailablePermissions[2].Value":true,"AvailablePermissions[3].Key":true,...etc"
ko.utils.postJson doesn't set the Content-Type request header to application/json. It will simply send the request as form encoded value. So use $.ajax instead which allows you to specify the correct content type header:
mappedModel.save = function(form) {
mappedModel.AvailablePermissions([]);
mappedModel.AvailableUsers([]);
mappedModel.AvailableGroups([]);
$.ajax({
url: '#Url.Action("Create", "Page")',
type: 'POST',
data: ko.toJSON(mappedModel),
contentType: 'application/json; charset=utf-8',
success: function(data) {
...do something
}
});
};
The Content-Type request header is used by ASP.NET MVC when trying to read the request in order to know how is this request being serialized.
In addition to that you might want to replace the IList<KeyValuePair<Guid, string>> types with IList<MyViewModel> where MyViewModel would be a view model class exposing two public properties: Key and Value. I am not sure that the JSON serializer would cope well with those KeyValuePair<Guid, string> type.