MVC3 jquery post serialize array - javascript

In my website there is a table, in every td, there is a div with <input> inside.
I run over the table and serialize every div and post it to the server.
for (var r = 0; r < tbodyRow.length; r++) {
var tbodyCols = tbodyRow[r].cells;
for (var c = 0; c < tbodyCols.length; c++) {
row = r + 1;
cell = c + 1;
div = $("#tbody tr:nth-child(" + row + ") td:nth-child(" + cell + ") :input").serialize();
if (div != "") {
$.post("../Contoller/Action?Mode=" + Mode, div, function () { });
}
tbodyCounter++;
};
};
and in the server - the action have an object as parameter that get it.
I would like to post all the list of the object (that i have in the divs) just once
and get it as List<T> in the server side.
is it possible ?

Yes, model binding allows to do that. Refer below article
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
Also refer below one for introduction
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Have the inputs inside the form tag and serialize form and send it.
$.post("#Url.Action("YourAction","YourController")",
$("#yourFormID").serailize(),function(data){
});
In the controller, you can use the model /viewmodel which your view was strongly typed to , as the parameter so that MVC model binding will bind that posted data to it.
[HttpPost]
public ActionResult YourAction(YourViewModel model)
{
//do something
}

Related

JSON Data not appering in Datatable. When Clicking any function it says no data avaliable

I m using AdminBSB Material design Admin panel for a project. Im getting JSON data from an API and displaying it on a DataTable . The Data showing in the table but when i click any function sorting/searching all the data disappear from the table and showing 0 data
dataType: 'json',
type: "GET",
success: function (data) {
$('#loading-data3').hide();
var i = 0;
var count = data.total;
console.log(count);
for (i = 0; i <= count; i++) {
$('#remaining-time').find('tbody').append(
"<tr><td>" + data.data[i].ASSIGNEE + "</td><td>" +
data.data[i].totalEstimateTime + "</td><td>" +
data.data[i].timeSpent + "</td><td>" +
data.data[i].remainTime + "</td></tr>"
);
}
}
});
sample screenshot
You are using DataTables... This plugin create some new elements dynamically on every draw (caused by ordering, searches, pagination, etc). If you want to add a new row to a Datatable already instantiated, you have to use the row.add() method.
You should have the DataTable instantiation somewhere in your code, possibly with an option object passed as argument. If you do not yet, assign a variable to the instance.
var myTable = $('#remaining-time').DataTable();
Then when you loop through your json data to add rows, it should look like this:
// Your loop through json
var count = data.total;
console.log(count);
for (i = 0; i <= count; i++) {
myTable.row.add([ // "myTable" refers to the Datable instance here.
data.data[i].ASSIGNEE,
data.data[i].totalEstimateTime,
data.data[i].timeSpent,
data.data[i].remainTime,
]);
}
Documentation

Controller does not catch JavaScript variable

I am working in ASP.NET Boilerplate (ABP) and AngularJS. I am using controllers (to upload files) with Kendo upload on frontend. To access controller I am using clicking kendo button clicking it like:
($("#files").data("kendoUpload")).options.async = vm.uploadOptions(onUpdate);
$('.k-upload-selected').click();
Function vm.uploadOptions(onUpdate) takes list of Ids and returns retObject like
var retObject = { saveUrl: '/ControllerName/ActionName?id=15&id=16', autoUpload: false, batch: true }
Now the actual question:
When I assign saveUrl in retObject like above or like
retObject.saveUrl = '/ControllerName/ActionName?id=195&id=196&id=197'
(ids hardcoded), the controller is entered (I have a breakpoint there) and I have a C# List with two elements.
When I assign url like:
vm.url = '/ControllerName/ActionName?fileId=' + fileIds[0];
len = fileIds.length;
for (var i = 1; i < len; i++) {
vm.url += '&fileId=' + fileIds[i];
}
retObject.saveUrl = vm.url;
the controller is not entered.
Finally (this is what I use in code now), when I assign like
vm.url = '?fileId=' + fileIds[0];
len = fileIds.length;
for (var i = 1; i < len; i++) {
vm.url += '&id=' + fileIds[i];
}
retObject.saveUrl = '/ControllerName/ActionName' + vm.url;
it does work - controller is entered with a proper list of ids.
When I copied dynamically generated (not working) string and assigned it as hardcoded it started working.
Why it happens, I mean: why exactly the same string initialized in different ways makes different results?

Object array gets overwritten by the last object

I have this array of objects being loaded:
$(document).ready(function () {
$("<div></div>").load("/Stats/Contents #stats", function () {
statcount = $(".list-group-item", this).length;
for (var j = 0; j < statcount; j++) {
statList.push(stat);
}
for (var i = 0; i < statcount; i++) {
statList[i].statId = document.getElementById("statId-" + (i + 1) + "").value;
statList[i].productDescription = document.getElementById("productType-" + (i + 1) + "").value;
statList[i].lastMeasuredInventoryAmount = document.getElementById("statLastMeasureAmount-" + (i + 1) + "").value;
}
)}
)}
.... and so on
Then I get the changed values and save them, however, in the ajax post call, all of the array objects are same (the last one assigned), looks like they get overwritten.
Any ideas? I saw these deferred/promise type code but not sure if there's simpler way.
Thanks.
It sounds like you take the statList array and then push that up to the server, with any respective change. Rather than building and maintaining a list like this, have you thought of switching it around and just grabbing the results out of the markup and building up the array at save point?
$("btnSave").on("click", function(e) {
var data = [];
$(".list-group-item").each(function() {
data.push({
statId: $(this).find(".statid").val(),
.
.
})
});
You wouldn't need to give every element an ID (but could) as my sample uses CSS classes to find the element within the current list item. Additionally, if these are inputs, you could serialize them from the root element more efficiently...

Typeform answers integration in server database

I am using webhooks of typeform to get the answers. Now I want to directly store the answers in my database.
For example, if a user is entering his/her name, then the answer should directly be stored in user model. To make it work i need some information from the question that it is user's name.
Is there any way of adding a hidden tag(name, age, gender) to identify the questions. I can not hard code the question ids, as i have a lot of forms with different types of questions.
If you want to store response in database table then you have to make it hard codded or create table while getting response.
i.e read question array from response and create table accordingly and store response in newly created table. On next time check if there is table is created or not, if yes then store value else create new table.
Here is my sample code to read response dynamically:
function renderData(data) {
var header = '', rows = '';
var questions = data.questions;
var responses = data.responses;
for (var j = 0; j < questions.length; j++) {
header += '<th>' + questions[j].question + '</th>';
}
for (var i = 0; i < responses.length; i++) {
rows += "<tr>"
for (var j = 0; j < questions.length; j++) {
if (responses[i].answers[questions[j].id] == undefined) {
rows += '<td> - </td>'
} else {
rows += '<td>' + responses[i].answers[questions[j].id] + '</td>';
}
}
rows += "</tr>"
}
$('table').append(
'<table>' + '<thead>' + header + '</thead>' + '<tbody>' + rows
+ '</tbody>' + '</table>');
};
Above function get data as response from typeform API and create table of your answer.
I hop it will helpful to you.
I suggest matching field titles with a with a regex. Since the field titles are in sentences, it's useful to match them in a specific order, and take fields that have already been matched out of the running. More specific fields should be matched first. This is similar to the cucumber testing tool which uses plain english.
Here's some code that I haven't tried running yet, to give an idea of what I'm getting at:
class TypeformReader() {
constructor(data) {
this.fields = data.form_response.definition.fields;
this.answers = data.form_response.answers;
this.read = [];
}
getAnswer(pattern, markRead = false, ignoreRead = true) {
for (let field of this.fields) {
if (ignoreRead && this.read.includes(field.id)) {
continue;
}
if (pattern.test(field.title)) {
for (let answer of this.answers) {
if (answer.field.id == field.id)
if (markRead) {
this.read.push(field.id);
}
return answer;
}
}
}
}
}
}
Here's an example of how to use this class. If you have a typeform for a dog yoga class that says "What's your name?" and "What's the name of your dog?" you'd want to match the longer one first (also included is "What's your email?" which is an email field and has the answer in the email key of the answer rather than text).
const reader = new TypeformReader(req.data);
const dogName = reader.getAnswer(/\bname\b.*\bdog\b/).text;
const name = reader.getAnswer(/\bname\b/).text;
const email = reader.getAnswer(/\bemail\b').email;

Dynamic Javascript Table

Does anybody know how to convert my data to table by using Javascript or JQuery, I got this data for example:
var data1 = ["1","3","5"]
var data2 = ["a","b","c"]
Once the data1 and data2 value is updated then the rows and columns are also automatic updated.
result:
etc:
No. Alphabet
1 a
3 b
5 c
In your .html file
<table class="myTable"></table>
In your .js file
function generateTable(data1, data2){
var $table = $('.myTable');
for (var i = 0; i < data1.length; i++){
var $aSingleContent = '<tr><td>'+data1[i]+'</td><td>'+data2[i]+'</td></tr>';
$table.append($aSingleContent);
}
}
function modifyData() {
var data1 = ["1","3","5"];
var data2 = ["a","b","c"];
generateTable(data1, data2);
}
--------------------------------Update-------
I put the code in jsfiddle
http://jsfiddle.net/ronansmith/daLf9t85/
remember to add External Resources of jQuery
I like the idea of creating a function to dynamically set the innerHTML of a div, propagating it with a table.
It should look something like this:
function generate_table(array1, array2) {
var html = '<table>';
// cycles through all the elements in the array
for (var i = 0; i < array1.length; i++) {
html += '<tr><td>' + array1[i] + '</td><td>' + array2[i] + '</td></tr>';
}
html += '</table>';
// places the table in the element
document.getElementById('content').innerHTML = html;
}
generate_table() takes in the two arrays and constructs a String, propagating it with the contents of the array in a for loop. Then it gets a div named content and sets its innerHTML to create the table.
In your webpage, be sure to include the div to which the table will be inserted:
<div id="content"></div>
You can also call generate_table() every time your array refreshes, and the table will update.
I hope this helps you!
there are two ways you can do this. one, you wrap a function/class around your data and have a "changedata" method that changes the data and updates the html or you have a setInterval that listens for changes to those variables and serves the changes to you markup. the former is much better than the latter in my opinion

Categories