Below is my Js code
function Table_to_Array() {
var myTableArray = $("#tbl_CGT tr").map(function () {
return $(this).find(':input').map(function () {
return this.value;
}).get();
}).get();
return myTableArray;
}
function send_to_server()
{
var result = Table_to_Array();
//var data = {
// Array: result
//};
var params = {
url: '#Url.Action("test2", "Annex1")',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional : true,
//data: JSON.stringify(data),
data: {Array:JSON.stringify(result)},
success: function (result) { alert('Ok! It worked.'); },
error: function (result) { alert('Warning! It failed.'); }
};
$.ajax(params);
}
It convert table values into an array and pass it to ActionResult in controller
It is creating array very well
But in controller it is coming null
public ActionResult test2(string[] Array)
{
string val = Array[1].ToString();
return View("Index");
}
What changes I need to do in it
Related
I have a MVC controller action with inputModel parameter which have list type property and , I ,m using $('form').serialize() to serialize the form content and append some of my custom data to serialized string, but inside the action method input model object the list property is empty,
Can any one help me , below is the code samples
My controller
[HttpPost]
public ActionResult Edit(ALDS.Web.Areas.Direct2M3.Models.ItemInputModel collection)
{ }
ItemInputModel class
public class ItemInputModel
{
//......Some property here..
public List<FabricCompositionInputModel> FabricCompositions { get; set; }
}
FabricCompositionInputModel class
public class FabricCompositionInputModel
{
public int ItemID { get; set; }
public string CompositionCode { get; set; }
public decimal Value { get; set; }
}
Ajax call
function save() {
var compositionData = generateCompositionForSave(); //Returns array
var data = $('form').serialize();
var d2 = JSON.stringify(compositionData);
var data2 = data + '&FabricCompositions=' + d2;
$.ajax({
type: 'POST',
dataType: 'json' ,
cache: false,
url: '/ItemMaster/Edit',
data: data2,
success: function (data, textStatus, jqXHR) {
sucess(data);
},
error: function (jqXHR, textStatus, errorThrown) {
failed(jqXHR);
}
});
}
Array generating function
function generateCompositionForSave() {
var arr = [];
var delClassList = $('#compositionContainer').find('.btnRemoveCompositions');
for (var c = 0; c < delClassList.length; c++) {
var row = $(delClassList[c]).closest('.row');
var code = row.find('.compositionCode').val();
var value = parseInt(row.find('.compositionValue').val());
arr.push({ItemID:0, CompositionCode:code, Value:value});
}
return arr;
}
Your not building the data correctly, and it needs to be
var compositionData = generateCompositionForSave();
var data = $('form').serializeObject(); // see function below
data['FabricCompositions'] = compositionData; // add the array to the serialized data
var data2 = JSON.stringify({ collection: data }), // stringify it
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8", // add contentType
dataType: 'json' ,
cache: false,
url: '#Url.Action("Edit", "ItemMaster")', // don't hard code your url's
data: data2,
success: function (data, textStatus, jqXHR) {
....
And add the following function (warning: this will not work correctly for a <select multiple> element)
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] === undefined) {
o[this.name] = this.value || '';
}
});
return o;
};
Note that if you generate your form controls correctly using a for loop or custom EditorTemplate for typeof FabricCompositionInputModel (refer Post an HTML Table to ADO.NET DataTable), for example
for(int i = 0; i < Model.FabricCompositions.Count; i++)
{
#Html.TextBoxFor(m => m.FabricCompositions[i].CompositionCode)
#Html.TextBoxFor(m => m.FabricCompositions[i].Value)
}
then all that is required is
var data = $('form').serialize();
$.ajax({
type: 'POST',
dataType: 'json' ,
cache: false,
url: '#Url.Action("Edit", "ItemMaster")',
data: data,
success: function (data, textStatus, jqXHR) {
HomeController:
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(CategoryOrderModel categories)
{
return Json(new { msg = "ok" });
}
public class CategoryOrderModel
{
public int DisplayOrder;
public int CategoryId;
}
View:
var operationCollection = new CategoryOrderModel();
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: JSON.stringify(operationCollection),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
The controller never gets the correct parameter??
UPDATED: I changed the code to accept the collection
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(List<CategoryOrderModel> categories)
{
return Json(new { msg = 'ok' });
}
View:
var collection = [];
var col1= new CategoryOrderModel(1,2);
collection.push(col1);
var col2= new CategoryOrderModel(2,5);
collection.push(col2);
$.ajax({
url: '/Home/SetDefaultHomeCategoryOrder/',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(collection) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
function CategoryOrderModel(displayOrder, categoryId) {
var self = this;
self.DisplayOrder = displayOrder;
self.CategoryId = categoryId;
}
Following are the errors in your code
1.Your model dont have getters and setters
public class CategoryOrderModel
{
public int DisplayOrder { get; set; }
public int CategoryId { get; set; }
}
2.Since it is javascript , operationCollection is model so it will not work instead deaclare a variable
var CategoryOrderModel =
{
"DisplayOrder": "7",
"CategoryId": "9"
};
$.ajax({
url: '#Url.Action("SetCategoryOrder", "Home")',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(CategoryOrderModel) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
As we know MVC works on the principle of name/value pair i.e. on Strongly type view along with Model binding.
Possibly you can do:
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: {'DisplayOrder' : 9 , 'CategoryId' : 1},
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
Notice data key/value data: {'DisplayOrder' : 9 , 'CategoryId' : 1},, this is somewhat similar to post a form in MVC.
Generally we use $('#formId').serialize() to send collection from view to controller with jquery/ajax.
You are trying to pass the data to controller "SetDefaultHomeCategoryOrder" or "SetCategoryOrder"
if Action name is SetCategoryOrder then type
url:#Url.Action('SetCategoryOrder','Home')
Your methods don't match from view you are calling SetDefaultHomeCategoryOrder but inside the controller it's called SetCategoryOrder
I am trying to pass the data of the view model to one js method and from there I need to pass the VM to another controller method to show the data.
here is what I have did:
$(document).ready(function () {
var content = GetHomeContent('/Home/CastContent');
if (content) {
saveBDContent('/Message/Details/', content);
}
});
function GetHomeContent(url) {
var modelData;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
contentType: 'application/json',
success: function (data) {
if (data) {
modelData = data;
}
},
error: function (data) {
status = false;
}
})
return modelData;
};
function saveBDContent(url, data) {
var status = false;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
if (data == "200") {
status = true;
}
},
error: function (data) {
status = false;
}
})
return status;
};
The problem am facing is , the content I retrived from the method show the namespace of the ViewModel. When I pass that to the new controlled the Viewmodel content is coming null.
Do I need to add anything to get/Pass the proper content ?
The Dummy method skeleton
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM);
}
I have missed out the JsonRequestBehavior.AllowGet in my controller method, I have added and the results are coming perfectly.
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM,JsonRequestBehavior.AllowGet);
}
and also I have set the HTTP status as post in the jquery method
Do something like that in the Controller:
public JsonResult QuickSave(BookEntry bookEntry) {
YourViewModel model = new YourViewModel();
return Json(model);
}
EDIT >> The associated Javascript code is :
$.ajax({
type: "POST",
url: 'The URL',
data: 'The JSON data',
dataType: "json",
success: function (theViewModel) {
// Do some JS stuff with your model
},
error: function (xhr, status, error) {
// Do some error stuff
}
});
I am trying to pass an array variable from ajax to controller,
but I am not getting the values in controller
below is my code
AJAX
function userDetailsClass() {
var userDetails = {};
userDetails.age = 12;
userDetails.Name = "Vignesh";
userDetails.lastName = "s";
debugger;
$.ajax({
url: "Home/userDetails",
data: JSON.stringify({
UserDetailsParam: userDetails
}),
responseType: "json",
success: successfn,
error: errorfn
});
function successfn(result) {
};
function errorfn(result) {
};
}
Controller
public ActionResult userDetails( string UserDetailsParam){
return View();
}
I also tried
public ActionResult userDetails( string[] UserDetailsParam){
return View();
}
Your code should be like this
$.ajax({
url: "Home/userDetails",
data: {
"UserDetailsParam":JSON.stringify(userDetails)//change this
},
responseType: "json",
success: successfn,
error: errorfn
});
Try with this
var userDetails = {"age":'12',"Name":'Vignesh',"lastName":'s'};
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data)
}
});
});
I am using the ajax call above to get a model back how would i use the model object in the success function. As in I need to be able to use the data like a views model like #model.Type lets say. how could i do that with the json data in the success?
The data object contains the properties passed down via the server.
You can then access them like:
var name = data.Name;
var testData = data.TestData;
Your Action could look like:
public JsonResult LeadCounts()
{
return Json(new { name = "Darren", testData = "Testing" });
}
In MVC3 you could do it like this:
public ActionResult LeadCounts()
{
var data = new { Count = 1, Something = "Something" };
return Json(data, JsonRequestBehavior.AllowGet);
}
In view:
$(document).ready(function () {
$.ajax({
url: 'LeadPipes/LeadCounts',
type: 'POST',
contentType: 'application/json',
async: false,
success: function (data) {
alert(data.Count);
}
});
});