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:
Related
I am getting an error when sending an array with a length greater than 250 to MVC controller. It works when array length is less than 250 items.
Client Code
function saveVD() {
var arr = [];
$.each($("#tablevd tbody tr"), function () {
arr.push({
invNo: $(this).find('td:eq(0)').html().trim(),
invDate: $(this).find('td:eq(1)').html().trim()
})
})
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "#Url.Action("Absorb","My")",
data: JSON.stringify({ 'arr': arr }),
success: function (result) {
},
error: function () {
}
})
}
Server Code
public class MyController : Controller
{
[HttpPost]
public JsonResult Absorb(CIVM[] arr)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
public class CIVM
{
public string invNo { get; set; }
public DateTime invDate { get; set; }
}
Below config changes may help you
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
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();
}
I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me
Model:
public class EmployeeModel
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
Controller :
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
public ActionResult GetUser()
{
return View();
}
public JsonResult GetAllUser(int EmpId)
{
List<EmployeeModel> employee = new List<EmployeeModel>();
string query = string.Format("Select * From Employee", EmpId);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
employee.Add(
new EmployeeModel
{
EmpId = int.Parse(reader["EmpId"].ToString()),
EmpName = reader.GetValue(0).ToString(),
Age = int.Parse(reader["Age"].ToString()),
Salary = int.Parse(reader["Salary"].ToString())
}
);
}
}
return Json(employee, JsonRequestBehavior.AllowGet);
}
}
ajax:
#{
ViewBag.Title = "Home Page";
var EmployeeModel = (List<second_day.Models.EmployeeModel>)Model;
}
<div id="id"></div>
<div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('p#getEmployee').click(function () {
GetEmployeeUsingAjax();
});
});
function GetEmployeeUsingAjax() {
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data:{"EmpId":EmpId},
dataType: 'json',
success: function (data) {
console.log(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
Here i Need to fetch the data when its success else through error if it doesnt
Am new to this platform can anyone help me
function GetEmployeeUsingAjax() {
var EmpId = 2;
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data: { "EmpId": EmpId },
dataType: 'json',
success: function (data) {
alert(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
// your code
}
plus string.Format("Select * From Employee where empid = {0} ",EmpId)
Please Check Below code :
var var EmpId = 2;
var abc = {
"EmpId": EmpId
};
$.ajax(
{
url: '/ControllerName/GetAllUser/',
type: "GET",
async: false,
dataType: "json",
contentType: "application/json;",
data: JSON.stringify(abc),
success: function (result) {
alert(data);
}
});
And Action Should Be :
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
}
Happy !!
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()
},
I have a view where i dynamically render checkbox items with razor. User can make adjustments and then i need to send form back to controller. If i send only one item i.e. row, it works fine, but if i try to send all of them i always get null. How can i collect form data properly. This is what i have at the moment.
public void SendData(List<SomeClass> myData)
{
var data = myData; //always null
}
public class SomeClass
{
public int Id { get; set; }
public int RoleId { get; set; }
public bool R { get; set; }
public bool W { get; set; }
public bool E { get; set; }
public bool D { get; set; }
}
And view:
<script type="text/javascript">
$(document).ready(function () {
var test = $("#myForm").serialize();
console.log(test);
test = JSON.stringify({ 'myData': test });
console.log(test);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Home/SendData',
data: test,
success: function () {
},
failure: function (response) {
}
});
});
</script>
<form id="myForm">
<div class="row control_group">
#Html.Hidden("Id", 1)
#Html.Hidden("RoleId", 1)
#Html.CheckBox("R", false)
#Html.CheckBox("W", false)
#Html.CheckBox("E", false)
#Html.CheckBox("D", false)
</div>
<div class="row control_group">
#Html.Hidden("Id", 2)
#Html.Hidden("RoleId", 2)
#Html.CheckBox("R", true)
#Html.CheckBox("W", true)
#Html.CheckBox("E", true)
#Html.CheckBox("D", true)
</div>
</form>
EDIT:
This is how i render items with razor
foreach (SomeObject x in items)
{
var menuName = someStringFromDb;
var permissions = x.MainItem.FirstOrDefault();
<div class="row control_group">
<div class="col-sm-4">#menuName</div>
<input name="Id" type="hidden" value="#permissions.Id"/>
<input name="RoleId" type="hidden" value=#permissions.RoleId />
<div class="col-sm-2">
#Html.CheckBox("R", #permissions.Read)
</div>
<div class="col-sm-2">
#Html.CheckBox("W", #permissions.Write)
</div>
<div class="col-sm-2">
#Html.CheckBox("E", #permissions.Edit)
</div>
<div class="col-sm-2">
#Html.CheckBox("D", #permissions.Delete)
</div>
</div>
}
EDIT 2
Thank you for your answer #Avi Fatal it got me this far. Problem i am facing now is this. Checkbox elements rendered by razor have two inputs, one is hidden and other one is shown. When i collect form data i am always getting last input value (hidden one, that's always false) How can i get true value?
Current data sent to controller (everything is false):
{"ajaxData":[{"Id":"1","RoleId":"1","R":"false","W":"false","E":"false","D":"false"},{"Id":"2","RoleId":"2","R":"false","W":"false","E":"false","D":"false"}]}
Collecting data like this (found similar problem here on SO):
var ajaxData = $('.control_group').map(function (i, group) {
var data = {};
$(group).find(':input').each(function () {
data[this.name] = this.value;
});
return data;
}).get();
ajaxData = JSON.stringify({ 'ajaxData': ajaxData });
console.log(ajaxData);
EDIT 3
With only .serialize() i get null as input parameter on controller, with JSON.stringify i get Count = 0, also empty. What am i missing?
HTML:
#model List<WebApplication3.Controllers.HomeController.SomeClass>
<form id="myForm">
#for (int i = 0; i < Model.Count; i++)
{
<div>Element</div>
#Html.HiddenFor(m => m[i].Id)
#Html.HiddenFor(m => m[i].RoleId)
#Html.CheckBoxFor(m => m[i].R)
#Html.CheckBoxFor(m => m[i].W)
#Html.CheckBoxFor(m => m[i].E)
#Html.CheckBoxFor(m => m[i].D)
}
</form>
<button id="send">SEND</button>
<script type="text/javascript">
$('#send').on('click', function () {
var data = $("#myForm").serialize();
console.log(data);
//data = JSON.stringify({ 'ajaxData': data });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/SendData',
data: data,
success: function () {
},
failure: function (response) {
}
});
});
</script>
Controller
public void SendData(IEnumerable<SomeClass> ajaxData)
{
var data = ajaxData;
}
It took me some time to understand the problem (-:
Anyway, I have created a small test, and it is working.
public class User
{
public string UserName { get; set; }
}
public void TestPost(List<User> users)
{
}
you need to serialize your data to json array of objects,
[{ 'UserName': "user 1" }, { 'UserName': "user 2" }] a little jquery manipulation... (see here: Convert form data to JavaScript object with jQuery)
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Home/TestPost',
data: JSON.stringify([{ 'UserName': "user 1" }, { 'UserName': "user 2" }]),
dataType: "json",
});