Sending Arrays from View to Controller in MVC - javascript

I am trying to send the following values from view to controller
var ParamAliasArray = new Object();
for (var i = 1; i <= 1; i++) {
ParamAliasArray[i] = $("#txtParamAlias" + i).val();
}
var ParamValueArray = new Object();
for (var i = 1; i <= 4; i++)
{
ParamValueArray[i] = new Array();
for (var j = 1; j <= 1; j++) {
ParamValueArray[i][j] = $("#txtParamValue" + i).val();
}
}
one is 1D array and other is 2D array I am passing as
jQuery.ajaxSettings.traditional = true
$.ajax({
type: 'Post',
dataType: 'json',
url: 'Register/GetRegDataFromuser',
data: JSON.stringify({ GloabalAppID: GlobalAppID,
TransactionID: TransactionID,
OwnerID: OwnerID,
ParamAliasArray: ParamAliasArray,
ParamValueArray: ParamValueArray }),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
console.debug(data);
},
error: function (data) {
console.debug(data);
}
});
I have written Action method as in
public ActionResult GetRegDataFromuser(int GloabalAppID, int TransactionID, string OwnerID, string[] ParamAliasArray, string[][] ParamValueArray)
{
---some logic--
}
So,I am not able to pass the array to the action method from View..Please help me out.
Thanks in advance.

you need to add ParamValueArray[i][j]=new Array(); this line.

Related

AJAX Call passing null values to controller

I'm trying to send data to the controller using this AJAX call of type POST but it's sending null values to the controller. Through this code I want to make new records in the Microsoft Dynamics 365 CRM database.
var formdata = new FormData();
var rowCount = $(".newRow").length;
var projectarray = [];
var datearray = [];
var amountarray = [];
for (var i = 0; i < rowCount; i++) {
projectarray[i] = $("#ProjectType_" + i).val();
datearray[i] = $("#ClaimExpenseDate_" + i).val();
amountarray[i] = $("#Amount_" + i).val();
}
formdata.append("projectarray", projectarray);
formdata.append("datearray", datearray);
formdata.append("amountarray", amountarray);
$.ajax({
url: "#Url.Action("SetClaimDetails", "Claim")",
type: "POST",
data: formdata,
processData: false,
contenttype: false,
success: function (data) {
debugger;
window.location.href = "ess/claim";
alert("Submit Successful!");
},
error: function (err) {
window.location.href = "";
alert("Submit Failed!");
}
});
Here is my controller method which is storing null values instead of the values passed by the AJAX call. And because of this I'm not able to create new records in the database.
public ActionResult SetClaimDetails(string projectarray, string datearray, string amountarray)
{
try
{
Entity item = new Entity("bam_expenseclaims");
item["bam_expdate"] = Convert.ToDateTime(datearray);
item["bam_amount"] = amountarray;
item["bam_project"] = new EntityReference("new_project", Guid.Parse(projectarray));
globalService.Connection.Create(item);
}
catch (Exception ex)
{
XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("TechnicalErrorAppender");
log.Error(string.Empty);
throw ex;
}
return View(Constant.CLAIMPATH);
}

Api from Asp core controller not receive all the value that FormData.append(key,value) appended

I want to upload files(image, setup file) and some other text string together.
This is my ajax code:
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
formData = new FormData();
for (var i = 0; i !== files.length; i++) {
var temp1 = files[i];
}
formData.append('temp', 1);
formData.append('temp', "ksjhdfksdjf");
$.ajax({
type: "POST",
url: "/Admin/FileUploadView/SaveEntity",
data: formData,
contentType: false,
processData: false,
beforeSend: function () {
tedu.startLoading();
},
success: function () {
},
error: function () {
}
});
}
This is my controller:
When I log all the files that formData object contain, everything is ok:
But I only receive 2 image's objects in the controller:
Now I want that I can receive all the files that I appended. Do you have any ideas, please help me.
You do not receive your temp in your controller.
js:
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
formData.append('temp', 1);
formData.append('temp', "ksjhdfksdjf");
//ajax
controller:
[HttpPost]
public async Task<IActionResult> SaveEntity(IList<IFormFile> files,List<string> temp)

mvc Ajax How to upate serialized model with formCollection

I have a page, which will send back the serialzed Model to the controller. In this case I'm using ajax.
In the View I have the following code:
#Html.Hidden("processViewModel", new Microsoft.Web.Mvc.MvcSerializer().Serialize(Model, SerializationMode.Signed))
And the controller looks like this:
[HttpPost]
public ActionResult PreviewSample([Deserialize]ProcessViewModel processViewModel /*FormCollection form*/)
and here is my ajax code:
function GetPreview() {
var json = $('form').serializeObject();
complete = false;
json['ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader'] = false; // $('input[name="ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader"]').is(':checked');
alert($('input[name="ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader"]').is(':checked'));
var jsonData = JSON.stringify(json);
var url = ROOT + '/request/previewsample/';
if (lastPreviewCall != undefined) {
if (lastPreviewCall.status != 200) {
lastPreviewCall.abort();
}
}
lastPreviewCall = $.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
// dataType: 'json',
data: jsonData,
otherParam: true,
async: true,
success: function (res) {
$('#preview').find('tbody').find('tr').remove();
var selected = $('.addressType:checked').attr('data-hideClass');
for (var i = 0; i < res.PreviewData.length; i++) {
var entry = '<tr>';
var row = res.PreviewData[i];
for (var u = 0; u < row.length; u++) {
if (u == 0 && selected == 'consumer') {
entry += '<td></td>';
}
else {
entry += '<td><span>' + row[u] + '</span></td>';
}
}
entry += '</tr>';
$('#preview').find('tbody').append(entry)
}
}
});
}
So now I have a checkbox, which is default true in this model and when I uncheck it, the ajax will send the serialized model back to the controller, but the checkbox has always the value true.
how can i update the model?
Thanks for any help.
The solution is to add
TryUpdateModel(processViewModel);
in the controller, and then is everything fine...

filter by a key/value from json Array

here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});

Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action

This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});

Categories