My json object becomes null when it reaches my controller function - javascript

I know this question has been asked many times, but this is different.
I have kendo grdi which i get selected and not selected type, the user have free role to make changes and that works. I did tried exmples like this Example1 ,Example2 and many others.
Now the problem is my json object that am trying to pass to the controller became null, I this is what i have tried below.
Can you please correct me if there's something wrong am doing ?
Javascript
JsonObj : This is what i get when i deselect from grid checkbox
[ { mailID: '10' , roleID: '5' , isMailSelected: 'false' } , {
mailID: '11' , roleID: '5' , isMailSelected: 'false' } , {
mailID: '19' , roleID: '9' , isMailSelected: 'false' } ]
function goToControllerSave() {
var jsonObj = displayFilterResults();
$.ajax({
url: '#Url.Action("Save", "Account")',
type: "POST",
dataType: "json",
traditional: true,
data: { myobj: jsonObj },
success: function (data) {
},
error: function (data) {
}
})
}
$(function () {
$('#Grid1').on('click', '.chkbx', function () {
var checked = $(this).is(':checked');
var grid = $('#Grid1').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set('isSelected', checked);
})
})
//My json obj: this returns results on Alert
function displayFilterResults() {
var items = "[";
var dataSource = $("#Grid1").data("kendoGrid").dataSource;
var filters = dataSource.filter();
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var filteredData = query.filter(filters).data;
items = items + " { mailID: '" + item.mailID + "' , roleID: '" +
item.roleID + "' , isSelected: '" + item.isSelected + "' } ,";
});
if (items.charAt(items.length - 1) == ',') {
items = items.substr(0, items.length - 1);
}
items = items + "]";
alert(items)
return items;
}
My conntroller
public class myItems
{
public string mailID { set; get; }
public string roleID { set; get; }
public string isSelected { set; get; }
}
[HttpPost]
public ActionResult Save(List<myItems> myobj)
{
--------------
--------------
}

In the examples you mention, json object is an actual object, not the string representation. Then JSON.stringify() is used to get string formatted using double quotation marks, removing spare spaces, etc. Unfortunately MVC application has trouble parsing json that doesn't look like this.
Since you create a string directly, you need to produce similar json format.
var json = '{"myobj":[';
json +='{mailID:"10",roleID:"5",isMailSelected:"false"},';
json+='{mailID:"11",roleID:"5",isMailSelected:"false"},';
json +='{mailID:"19",roleID:"9",isMailSelected:"false"}'
json +=']}';
$.ajax({
url: '#Url.Action("Save", "Account")',
type: "POST",
contentType: "application/json",
dataType: 'html',
data: json,
success: function (data) {
},
error: function (data) {
}
})
In the class I have updated the name of member isSelected, cause I saw it didn't match json and I assume you changed it to isMailSelected.
public class myItems
{
public string mailID { set; get; }
public string roleID { set; get; }
public string isMailSelected { set; get; }
}
In my controller I have the same you posted
[HttpPost]
public ActionResult Save(List<myItems> myobj)
{
return View();
}

Related

How to Pass Jsonstringfy object with other parameters

I want pass more parameter with json stringify() but when passing other variable getting null value. please let me know right way of passing more variable .
I have tried this
data: {model:JSON.stringify(arr), buildingid ,shopid,post},
$("#btnArchive").click(function () {
var Buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
var Post = $("#SelectedValue").val();
var arr = [];
debugger;
//Loop through the Table rows and build a JSON array.
var customers = new Array();
$(".tblSavingCollChk:checked").each(function () {
var row = $(this).attr("chkid");
alert(row);
debugger;
//customers.push(row);
arr.push({ Id: row });
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Archive/UpdateStatus",
data: JSON.stringify(arr),
dataType: "json",
success: function (r) {
if (r == true) {
alert("Record Updated successfully");
document.location = '#Url.Action("ArchiveList","Archive")';
}
},
error: function (err) {},
});
});
Controller action
public ActionResult UpdateStatus([FromBody] ArchiveViewModel[] model,string buildingid, string shopid, string Post)//List values)
{}
If you want to pass more variable,I have a work demo like below, you can refer to it:
remove [Frombody] and dataType,contentType
In the controller:
public class jsonPostController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult GetData(Author jsonInput ,string cc, string buildingid, string shopid)
{
return View();
}
}
Index view:
<input type="button" id="btnGet" value="submit" />
<input id="BuildingId" value="aa" type="hidden" />
<input id="ShopId" value="aaa" type="hidden" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {
$("#btnGet").click(function ()
{
// Initialization
var jsonInput = {Id: 23, Name: "John" };
var buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
$.ajax(
{
type: 'POST',
url: '/jsonPost/GetData',
data: {
jsonInput: jsonInput,
cc: "cc", buildingid: buildingid, shopid: shopid
},
});
});
});
</script>
Author:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
}
result:

How send complex data type with ajax to the action in controller in ASP.NET MVC

In my ASP.NET framework MVC project I must send below two data (first data is a list of string and second data is a GUID) with ajax to the action in controller:
0: "{Key:'052c5941-233a-4bd2-80e1-7cfffa34ca44',Value:'Salary1'}"
1: "{Key:'00000000-0000-0000-0000-000000000004',Value:'Salary2'}"
2: "{Key:'00000000-0000-0000-0000-000000000005',Value:'Salary3'}"
3: "{Key:'00000000-0000-0000-0000-000000000003',Value:'Salary4'}"
4: "{Key:'00000000-0000-0000-0000-000000000001',Value:'Salary5'}"
5: "{Key:'00000000-0000-0000-0000-000000000002',Value:'Salary6'}"
and
"6a580cf1-2f05-4621-8a67-8fe0bdd559c2"
My action is as below
public JsonResult DigestFile(List<string> value1, string pointId)
{
....
}
How can I do this? Any help will be appriciated!
You can use HTTP post as the following code to do it, you just creat a class with Key and Value, and use it in Controller with a String variable, on a HTTP post Function.
I am not expert in C# I did translate online from my VB code that work well.
In your Views (.cshtml) :
<input id="Button1" type="button" value="button" onclick="SaveMe()" />
<script>
function SaveMe() {
var GUID = '6a580cf1-2f05-4621-8a67-8fe0bdd559c2';
// Creat Object
var lineItems = new Object();
lineItems.Entrys = new Array();
// Example Filling your object, but of course you can get data from another place ...
lineItems.Entrys[0] = new Object({ Key: '052c5941-233a-4bd2-80e1-7cfffa34ca44', Value: 'Salary1' });
lineItems.Entrys[1] = new Object({ Key: '00000000-0000-0000-0000-000000000004', Value: 'Salary2' });
lineItems.Entrys[2] = new Object({ Key: '00000000-0000-0000-0000-000000000005', Value: 'Salary3' });
$.ajax({
type: "POST",
url: "/Home/AjaxMethodDigestFile",
data: JSON.stringify({ Entrys: lineItems.Entrys, GUID: GUID }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { alert(response.message); },
failure: function (response) { alert("failure"); },
error: function (response) { alert("error"); }
});
}
</script>
In your Models:
namespace MyModel1.ViewModel
{
public class MyClass1
{
public string Key { get; set; }
public string Value { get; set; }
}
}
In your Controllers:
[HttpPost]
public JsonResult AjaxMethodDigestFile(ICollection<MyModel1.ViewModel.MyClass1> Entrys, string GUID)
{
string message = "";
int counter = 0;
foreach (var entry in Entrys)
{
// How to use this data example
string Key = entry.Key;
string Value = entry.Value;
counter += 1;
message += Value + ": " + Key + Constants.vbCrLf;
}
// The following lines are not necessary, it's just an example code to know what happen and return it to client side ...
if (counter > 0)
message = counter.ToString() + " Entrys received" + Constants.vbCrLf + message;
else
message = "no entrys";
var response = new { counter, message };
return Json(response);
}

Passing Multiple JSON objects via AJAX to ASP.Net PageMethod

I am trying to pass two JSON Objects to my Page Method via AJAX
I created a class in Code Behind and created a JSON Object Array in javascript.
Following are my two classes and Page Method
public class userModel
{
public string userid { get; set; }
public string Name { get; set; }
}
public class companyModel
{
public string companyid { get; set; }
public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{
return "";
}
And Following is my Javascript
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: []};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company = {companyid: "4", Name:"TEST COMPANY"};
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
Up till this point my code is working fine.
What I want to do is to pass the company object to the Page Method as well like this
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}
You could merge the models into one model.
public class TestJsonModel
{
public UserModel UserModel { get; set; }
public CompanyModel CompanyModel { get; set; }
}
Then action looks like;
[WebMethod]
public static string TestJsonMethod(TestJsonModel model)
Also, Ajax request post data looks like;
data: JSON.stringify({UserModel:obj,CompanyModel:company})
I was trying out different ways of doing it and this one worked.
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: [], company: {}};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company_ = {companyid: "4", Name:"TEST COMPANY"};
obj.company = company_;
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
And the Code behind Page Method remains same.
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

MVC Controller and data received

I am trying to send json to my mvc action controller, I searched and researched on the web, but I always receive the object in my controller with all "null" fieds.
I tryed to send a string instead then an object but same result, a null string.
I really don't know what could be wrong:
Class:
namespace TestUser.Models
{
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Sex { get; set; }
public string Transfer { get; set; }
public string PercTransf { get; set; }
}
}
Controller:
[HttpPost]
public ActionResult CheckUser( User dati)
{
if (dati != null)
{
if (string.IsNullOrEmpty(dati.Name))
return Json("Insert the name");
if (string.IsNullOrEmpty(dati.Surname))
return Json("Insert the surname");
if (dati.Sex != "m" && dati.Sex != "f")
return Json("Insert the sex");
return Json("OK");
}
else
{
return Json("No valid data");
}
}
Ajax:
function checkAndSaveData() {
var obj = new Object();
obj.Name = $("#nome").val();
obj.Surname = $("#cognome").val();
obj.Email = $("#email").val();
obj.Sex = $('#selectSesso').find(":selected").val();
obj.Transfer = "no";
obj.PercTransf = "0";
if ($('#trasferte:checked').val() == "on") {
obj.Transfer = "si";
obj.PercTransf = $("#tempotrasf").val();
};
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("CheckUser")',
data: JSON.stringify({ obj }),
success: function (json) {
if (json == "ok") {
$.ajax({
type: 'post',
dataType: 'json',
url: "#Url.Action("Save")",
success: function (json) {
if (json == "ok") {
alert();
} else {
alert(json);
}
},
});
} else {
alert(json);
}
},
});
}
You don't seem to be sending the dataObject object in the ajax request.
Try:
data: { JSON.stringify(obj) }
Also, the object you pass in the data field of the ajax request doesn't need to be on a 'dati' property of an object.
MVC should figure out the rest!
I always use fiddler for debugging issues like this to check the json your sending in the http request is as you'd imagine :)
your class properties and javascript properties should be same, then your controller action parameter name should match with jason string. so use like this JSON.stringify({"dati": obj });
There were many edits in the question so I'm going to publish full code. This worked for me when testing.
Javascript code
var obj = new Object();
obj.name = "name";
obj.surname = "cognome";
obj.email = "email";
obj.sex = 'm';
obj.transfer = "no";
obj.perctrasf = "0";
$.ajax({
type: 'post',
contentType: 'application/json',
dataType: 'json',
url: '#Url.Action("CheckUser")',
data: JSON.stringify({ dati: obj }),
success: function (json) {
if (json == "ok") {
alert("ok");
} else {
alert(json);
}
},
});
Controller
[HttpPost]
public ActionResult CheckUser(User dati)
{
return Json(dati);
}
Model
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Sex { get; set; }
public string Transfer { get; set; }
public string PercTransf { get; set; }
}

pass jquery array of objects to mvc action which accepts a list object

I have a form in my view which has only one textarea input initially and user can add more textarea inputs if he wants with jquery. My problem is related to second case. After submitting the form i am getting an array of objects in console but when i am passing this array to mvc action in my controller it is coming to be null.
I have tried these solution but did not succeed:
Send array of Objects to MVC Controller
POST a list of objects to MVC 5 Controller
here is my code:-
jquery code:
$('body').on('submit', '#addTextForm', function () {
console.log($(this));
var frmData = $(this).serializeArray();
console.log(frmData);
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify({ obj: frmData }),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
MVC action:
[HttpPost]
public string UploadText(SliderTextList obj)
{
return "success";
}
my object class:
public class SliderText
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("SlideName")]
public string SlideName { get; set; }
[JsonProperty("Content")]
public string Content { get; set; }
}
public class SliderTextList
{
public List<SliderText> AllTexts { get; set; }
}
I have to store the Content in json file with Id and SlideName, so i think i have to pass a list object in mvc action Uploadtext which is coming out to be null always. Please help.
$(document).ready(function(){
$('body').on('submit', '#addTextForm', function () {
var listData=[];
var oInputs = new Array();
oInputs = document.getElementsByTag('input' );
var k=1;
for ( i = 0; i < oInputs.length; i++ )
{
if ( oInputs[i].type == 'textarea' )
{
var obj=new Object();
obj.Id=k;
obj.SlideName=oInputs[i].Name;
obj.Content=oInputs[i].Value;
K=parseInt(k)+1;
listData.push(obj);
}
}
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify(listData),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
});
Since the sever side expects a string as argument obj as a query string I think this is what you need.
data: {
obj: JSON.stringify(frmData)
},
as an alternative using as Stephen suggested on the comments
data: {
obj: $('#addTextForm').serialize()
},

Categories