Ajax function not showing JSON List of Dates (Mvc5) - c#

In my MVC5 View, I´am calling a JSON function.
The JSON function returns a AvaliableDates model, wich have a Userld(string) and a LIST of DateTime objects defined.
My view is only able to read Userld but DateTime-objects appears as "undefined"
Can anyone see why I am not getting JSON DateTime LIST values in my view?
My JSON function:
public JsonResult GetFreeAppointmentDays()
{
List<DateTime> avaliableBookingDays = new List<DateTime>();
DateTime x1 = new DateTime(2017, 04, 11, 0, 0, 0);
DateTime x2 = new DateTime(2017, 04, 12, 0, 0, 0);
avaliableBookingDays.Add(x1.Date);
avaliableBookingDays.Add(x2.Date);
useravaliableDates AvaliableDates = new useravaliableDates()
{
UserIDs = "4,5,2,0,0,0,2",
Avdata = avaliableBookingDays
};
return Json(AvaliableDates, JsonRequestBehavior.AllowGet);
}
Here is my View, with AJAX call:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<div id="divshow"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Home/GetFreeAppointmentDays",
dataType: "json",
success: function (data) {
$('#divshow').append(data);
var items = '';
$.each(data.Avdata, function (i, item) {
var row = "UserIDs are: " + data.UserIDs + " Date " + i + " -> " + item[i].Date + "<br/>"
$('#divshow').append(row);
});
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
STRANGE: My JSON function return this
{"UserIDs":"4,5,2,0,0,0,2","Avdata":["\/Date(1491861600000)\/","\/Date(1491948000000)\/","\/Date(1492034400000)\/","\/Date(1492207200000)\/","\/Date(1492466400000)\/"]}

You are getting date in milliseconds format.
Convert the C# date object to a string format and change Avdata property to a List<String>
avaliableBookingDays.Add(x1.ToString("yyyy-MM-ddTHH:mm:ss"));
avaliableBookingDays.Add(x2.ToString("yyyy-MM-ddTHH:mm:ss"));
Then convert it to a javascript date object:
var row = "UserIDs are: " + data.UserIDs + " Date " + i + " -> " + new Date(item); + "<br/>"

You need a function which convert one date like \/Date(1491861600000)\/ to real one. For this you can use replace method.
function parseDate(value){
var newDate=new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
return newDate.getDate()+'/'(newDate.getMonth()+1)+'/'+newDate.getFullYear()
}
In your each method use parseDate function which I create above:
$.each(data.Avdata, function (i, item) {
var row = "UserIDs are: " + data.UserIDs + " Date " + i + " -> " + parseDate(item)+ "<br/>"
$('#divshow').append(row);
});

Related

How to draw line for real time flot?

Starting from here: How do I display a Json random number in a real-time Flot chart?, I managed to display a random number on a flot chart. The x axes is the current time's second. The problem I have is that now on my chart is shown only a point (current value). What I want is to display a real time line according to the values of the random number. How could I do this? I hope I made myself understood.
Here is my cod:
In C#:
if (method == "rnd")
{
//Current second
this.Page.Response.ContentType = "application/json1";
DateTime now = DateTime.Now;
int sec = now.Second;
Random rnd = new Random();
int nr = rnd.Next(1, 100); // creates a number between 1 and 99
var str = "{\"sec\":" + sec.ToString() + ",\"val\":" + nr.ToString() + "}";
var json2 = new JavaScriptSerializer().Serialize(str);
this.Page.Response.Write(json2);
}
My ASP page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MultiTrenduri.aspx.cs" Inherits="WebApplication2.MultiTrenduri" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/flot/jquery.flot.min.js"></script>
<script src="Scripts/flot/jquery.flot.time.js"></script>
<script src="Scripts/flot/jquery.flot.symbol.js"></script>
<script src="Scripts/flot/hashtable.js"></script>
<script src="Scripts/flot/jquery.flot.axislabels.js"></script>
<script src="Scripts/flot/jquery.numberformatter-1.2.3.min.js"></script>
<link href="Flot/examples.css" rel="stylesheet" />
<script type="text/javascript">
var sc = [], num = [];
function test2() {
$.ajax({
type: 'POST',
url: ('ajax.aspx?meth=') + "rnd",
contentType: 'application/json2; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
global: false,
timeout: 120000,
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(data);
$('#azi').html(obj.sec);
$('#nr').html(obj.val);
var sc = [], num = [];
sc.push(obj.sec);
num.push(obj.val);
data = [[[sc, num]]];
//var afis = [[[data]]];
//$('#afs').text(afis.join(" * "));
//show the data in a list in body
var items = [];
$.each(data, function (key, val1) {
items.push("<li><a href=#'" + key + "'>" + val1 + "</a></li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
//START: PLOT IN TIMP REAL
$(function () {
var plot = $.plot("#placeholder", data,
{
series: {
shadowSize: 0 // Drawing is faster without shadows
},
points: { show: true },
line: { show: true },
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: true
}
});
// plot.setData(data); //to reset data
// plot.draw(); //to redraw chart
});
// plot.draw();
//END: PLOT IN TIMP REAL
},
error: function (jqXHR, textStatus, errorThrown) {
window.alert(errorThrown);
}
});
}
window.setInterval(test2, 1000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="azi"></div>
<div id="nr"></div>
<div class="demo-container">
<div id="placeholder" class="demo-placeholder">
</div>
</div>
</div>
</form>
</body>
</html>
Maybe is someone which needs to do the same. This is how I managed to do it.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/flot/jquery.flot.min.js"></script>
<script src="Scripts/flot/jquery.flot.time.js"></script>
<script src="Scripts/flot/jquery.flot.symbol.js"></script>
<script src="Scripts/flot/hashtable.js"></script>
<script src="Scripts/flot/jquery.flot.axislabels.js"></script>
<script src="Scripts/flot/jquery.numberformatter-1.2.3.min.js"></script>
<link href="Flot/examples.css" rel="stylesheet" />
<%-- Library for TOOLTIP:--%>
<script src="Scripts/flot/jquery.flot.crosshair.js"></script>
<!-- CSS -->
<%--<style type="text/css">
#placeholder {
width: 1000px;
height: 500px;
text-align: center;
margin: 0 auto;
}
</style>--%>
<%-- <link href="Flot/examples.css" rel="stylesheet" />--%>
<%-- <script src="Scripts/jquery-1.4.1.js"></script>
<script src="Scripts/flot/jquery.flot.js"></script>--%>
<script type="text/javascript">
var sc = [], num = [];
var data = [];
var dataset;
var totalPoints = 100;
var updateInterval=30 ;
var now = new Date().getTime();
var t;
var multipleCalls, multCalls;
var input = document.getElementById('input');
var st;
/* window.onload = function f1() {
document.getElementById('updateInterval').value = 90;
}
function f2() {
// document.getElementById('up2').value = document.getElementById('up1').value
var updateInterval = document.getElementById('updateInterval').value;
// window.alert(updateInterval);
}*/
$(function () {
function test2() {
$.ajax({
type: 'GET',
url: ('ajax.aspx?meth=') + "rnd",
contentType: 'application/json2; charset=utf-8',
dataType: 'json',
//async: true,
//cache: false,
//global: false,
// timeout: 120000,
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(data);
$('#azi').html(obj.sec);
$('#nr').html(obj.val);
t = obj.val;
},
error: function (jqXHR, textStatus, errorThrown) {
window.alert(errorThrown);
}
});
}
function apel() {
test2();
$('#fn').html(t);
updateInterval = document.getElementById('updateInterval').value;
}
function GetData() {
data.shift();
data.slice(1);
while (data.length < totalPoints) {
// var y = Math.random() * 100;
var y = t;
var temp = [now += updateInterval, y];
data.push(temp);
}
}
$("#up").val(updateInterval).change(function () {
var vv = $(this).val();
if (vv && !isNaN(+vv)) {
updateInterval = +vv;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var options = {
series: {
lines: {
show: true,
lineWidth: 1.2,
fill: false
}
},
xaxis: {
mode: "time",
tickSize: [2, "second"],
tickFormatter: function (v, axis) {
var date = new Date(v);
if (date.getSeconds() % 5 == 0) {
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
var w = hours + ":" + minutes + ":" + seconds;
return w;
} else {
return "";
}
},
axisLabel: "Time",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10
},
grid: {
hoverable: true,
clickable: true
},
yaxis: {
min: 0,
max: 100,
tickSize: 5,
tickFormatter: function (v, axis) {
if (v % 10 == 0) {
return v + "%";
} else {
return "";
}
},
axisLabel: "CPU loading",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 6
},
legend: {
labelBoxBorderColor: "#fff"
}
};
//START TOOLTIP
/* $("#placeholder").bind("plothover", function (event, pos, item) {
if ($("#enablePosition:checked").length > 0) {
var str = "(" + pos.x.toFixed(2) + ", " + pos.y.toFixed(2) + ")";
$("#hoverdata").text(str);
}
if ($("#enableTooltip:checked").length > 0) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
$("#tooltip").html(item.series.label + " of " + x + " = " + y)
.css({ top: item.pageY + 5, left: item.pageX + 5 })
.fadeIn(200);
} else {
$("#tooltip").hide();
}
}
});
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label);
plot.highlight(item.series, item.datapoint);
}
});
*/
//END TOOLTIP
st = $(document).ready(function f1() {
test2();
GetData();
dataset = [
{ label: "CPU", data: data }
];
$.plot($("#placeholder"), dataset, options);
function stop() {
//window.alert("Stop");
//multipleCalls.clearTimeout();
window.clearTimeout(updateInterval);
}
function update() {
test2();
GetData();
$.plot($("#placeholder"), dataset, options)
multipleCalls = setTimeout(update, updateInterval);
multCalls = multipleCalls;
}
update();
});
});
</script>
</head>
<body>
//Stops the graph
<button onclick="clearInterval(multipleCalls)">Stop</button>
<div id="header">
<div id="azi"></div>
<div id="nr"></div>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>Time between updates: <input id="up" type="text" value="" style="text-align: right; width:5em"/> milliseconds</p>
</div>
</body>
</html>

How to add auto complete json for dynamically generated textboxes in asp.net

I am trying to generate dynamic html textboxes in my aspx page and on these textboxes i want to add the value using autocomplete facility. I try my best to do so. I try almost every single question's answer of stackoverflow. But nothing is working here my script which generate new textbox dynmacally
<script type="text/javascript">
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
// newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
// '<input type="text" name="textbox' + counter +
// '" id="textbox' + counter + '" value="" class="auto">');
newTextBoxDiv.after().html('<div class="fields-left"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter+1 + '" class="auto"/> </div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
Html code
<div id="TextBoxDiv1" class="fields" >
<div id="TextBoxesGroup">
</div>
</div>
<input type='button' value='Add Button' id='addButton'/>
<input type='button' value='Remove Button' id='removeButton'/>
</div>
and I am trying this json code for fetching data for very first textbox that generate automatically. First I think for write this script for everytextbox which generate dynamically but this process will be so lengthy and wrong way to do this thing. But this is not working for me
<script type="text/javascript">
$(document).ready(function () {
SearchText2();
});
function SearchText2() {
$("#textbox2").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById('textbox2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
Please experts tell me why this json is working for me
Thanks
Please use following code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="Web.Home" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var counter = 2;
$(document).ready(function () {
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var $wrap = $('#TextBoxesGroup');
var dynamichtml = '<div class="fields-left" id="divleft_' + counter + '"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right" id="divright_' + counter + '"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div>';
$wrap.append(dynamichtml);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxesGroup").find("#divleft_" + counter).remove();
$("#TextBoxesGroup").find("#divright_" + counter).remove();
});
$(".auto").live("focus", function () {
$(this).autocomplete({
minLength: 2,
source: function (request, response) {
var textval = request.term; // $(this).val();
$.ajax({
url: "Home.aspx/GetAutoCompleteData", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ code: textval }),
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}, select: function (event, ui) {
return false;
}
});
});
});
</script>
<style type="text/css">
.ui-menu { width: 150px; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="TextBoxDiv1" class="fields" >
<div id="TextBoxesGroup">
</div>
</div>
<input type='button' value='Add Button' id='addButton'/>
<input type='button' value='Remove Button' id='removeButton'/>
</div>
</form>
</body>
</html>
In .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace Web
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
[WebMethod]
public static List<string> GetAutoCompleteData(string code)
{
List<string> list = new List<string>();
list.Add("delhi");
list.Add("noida");
list.Add("gurgaon");
return list.Where(i => i.StartsWith(code)).ToList();
}
}
}
Please add js file as below
I would suggest you to use global variable say data to store the json response retirned for autocomplete.
and then use the same data to bind autocomplete after appending the contents.
$('#newTextBoxDiv input').autocomplete(data);

DataTable equivalent in Jquery to store data?

I have a form on which I am adding rows dynamically using Jquery.
Please take a look: DEMO
Now I want to save the data of all rows that has been added in my database using Jquery Ajax call on click event of SAVE button. The point where I am stuck is .. I am not sure how should I extract data of all rows and send it to the webmethod. I mean had it been c# I could have used a DataTable to store data of all rows before sending it to DataBase. I think I should create a string seperated by commas and pipe with data of each row and send it to webmethod. I am not sure if its the right approach and also how this is to be done (ie. creating such a string).
HTML
<table id="field">
<tbody>
<tr id="row1" class="row">
<td> <span class='num'>1</span></td>
<td><input type="text" /></td>
<td><select class="myDropDownLisTId"> <input type="text" class="datepicker" /></select></td><td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>
<button type="button" id="btnsave">SAVE</button>
2 suggestions:
To keep it as close as what you already have, you could just enclose your table in a form tag, and then you could just submit the form (use something like the jQuery Form plugin to submit it via Ajax). The trickiest part will be to bind that data to action parameters. You may be able to receive it in the form of an array, or you could default to looping through properties of the Request.Form variable. Make sure you generate proper names for those fields.
I think the cleanest way to do it would be to have a JavaScript object holding your values, and having the table generated from that object, with 2-way bindings. Something like KnockoutJS would suit your needs. That way the user enters the data in the table and you'll have it ready to be Json-serialized and sent to the server. Here's a quick example I made.
I wouldn't recommend that approach, but if you wanted to create your own string, you could do something along those lines:
$("#btnsave").click(function () {
var result = "";
$("#field tr").each(function (iRow, row) {
$("td input", row).each(function (iField, field) {
result += $(field).val() + ",";
});
result = result + "|";
});
alert(result);
});
You will have problems if the users types in a comma. That why we use well known serialization formats.
use ajax call on save button event...
like this
$(document).ready(function () {
$('#reqinfo').click(function () {
// debugger;
var emailto = document.getElementById("emailid").value;
if (emailto != "") {
$.ajax({
type: "GET",
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
// data: dat,
Accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// debugger;
},
error: function (result) {
// debugger;
}
});
}
else {
//your validation message goes here
return false;
}
});
});
and add you all data in quesry string and transfer it to webservice..
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto + "data1=" + data1,
<script type="text/javascript">
var _autoComplCounter = 0;
function initialize3(_id) {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}
google.maps.event.addDomListener(window, 'load', initialize3);
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
function GetDynamicTextBox(value) {
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
return '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "' + value + '" onkeypress = "calcRoute();" />' +
'<input type="button" class="superbutton orange" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
if (document.getElementById('number').value < 3) {
document.getElementById('number').value = value;
var div = document.createElement('DIV');
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var ht = '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "" onkeypress = "calcRoute();" class="clsgetids" for-action="' + _id + '" />' +
'<input type="button" class="superbutton orange" value="#Resources.SearchOfferRides.btnRemove" onclick = "RemoveTextBox(this); calcRoute();" />';
div.innerHTML = ht;
document.getElementById("TextBoxContainer").appendChild(div);
setTimeout(function () {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}, 100);
document.getElementById("TextBoxContainer").appendChild(div);
}
else {
alert('Enter only 3 stop point. !!');
}
}
function RemoveTextBox(div) {
//calcStopPointRoute();
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('number').value = value;
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
// window.onload = RecreateDynamicTextboxes;
</script>
And get the value from textbox:
#region stop point
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues != null)
{
for (Int32 i = 0; i < textboxValues.Length; i++)
{
if (textboxValues.Length == 1)
{
model.OptionalRoot = textboxValues[0].ToString();
}
else if (textboxValues.Length == 2)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
}
else if (textboxValues.Length == 3)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
model.OptionalRoot3 = textboxValues[2].ToString();
}
else
{
model.OptionalRoot = "";
model.OptionalRoot2 = "";
model.OptionalRoot3 = "";
}
}
}
#endregion
Short answer:
DataTable equivalent in javascript is Array of custom object (not exact equivalent but we can say that)
or
you roll your own DataTable js class which will have all the functions and properties supported by DataTable class in .NET
Long answer:
on client side(aspx)
you define a class MyClass and store all your values in array of objects of that class
and then pass that array after stingyfying it to web method
JSON.stringify(myArray);
on the server side(codebehind)
you just define the web method to accept a list of objects List<MyClass>
PS: When calling web method, Asp.net automatically converts json array into List<Object> or Object[]
Loooong answer (WHOLE Solution)
Page aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="App_Themes/SeaBlue/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
function MyClass(title,option,date) {
this.Title = title;
this.Option = option;
this.Date = date;
}
function GetJsonData() {
var myCollection = new Array();
$(".row").each(function () {
var curRow = $(this);
var title = curRow.find(".title").val();
var option = curRow.find(".myDropDownLisTId").val();
var date = curRow.find(".datepicker").val();
var myObj = new MyClass(title, option, date);
myCollection.push(myObj);
});
return JSON.stringify(myCollection);
}
function SubmitData() {
var data = GetJsonData();
$.ajax({
url: "testForm.aspx/PostData",
data: "{ 'myCollection': " + data + " }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
}
$(document).ready(function () {
filldd();
CreateDP();
var rowstring = "<tr class='row'><td class='number'></td><td><input type='text' class='title'/></td><td><select class='myDropDownLisTId'/><input type='text' class='datepicker'/></td><td><input type='submit'></input></td></tr>";
$("#addField").click(function (event) {
$("#field tbody").append(rowstring);
filldd();
CreateDP();
if ($("td").hasClass("number")) {
var i = parseInt($(".num:last").text()) + 1;
$('.row').last().attr("id", "row" + i);
$($("<span class='num'> " + i + " </span>")).appendTo($(".number")).closest("td").removeClass('number');
}
event.preventDefault();
});
$("#deleteField").click(function (event) {
var lengthRow = $("#field tbody tr").length;
if (lengthRow > 1)
$("#field tbody tr:last").remove();
event.preventDefault();
});
$("#btnsave").click(function () {
SubmitData();
});
});
function filldd() {
var data = [
{ id: '0', name: 'test 0' },
{ id: '1', name: 'test 1' },
{ id: '2', name: 'test 2' },
{ id: '3', name: 'test 3' },
{ id: '4', name: 'test 4' },
];
for (i = 0; i < data.length; i++) {
$(".myDropDownLisTId").last().append(
$('<option />', {
'value': data[i].id,
'name': data[i].name,
'text': data[i].name
})
);
}
}
function CreateDP() {
$(".datepicker").last().datepicker();
}
$(document).on('click', 'input[type="submit"]', function () {
alert($(this).closest('tr')[0].sectionRowIndex);
alert($(this).closest('tr').find('.myDropDownLisTId').val());
});
</script>
</head>
<body>
<form id="frmMain" runat="server">
<table id="field">
<tbody>
<tr id="row1" class="row">
<td>
<span class='num'>1</span>
</td>
<td>
<input type="text" class="title"/>
</td>
<td>
<select class="myDropDownLisTId">
</select>
<input type="text" class="datepicker" />
</td>
<td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">
Add Field</button>
<button type="button" id="deleteField">
Delete Field</button>
<button type="button" id="btnsave">
SAVE</button>
</form>
</body>
</html>
CodeBehind:
public partial class testForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void PostData(List<MyClass> myCollection)
{
Console.WriteLine(myCollection.Count);
}
}
public class MyClass
{
string title;
public string Title
{
get { return title; }
set { title = value; }
}
string option;
public string Option
{
get { return option; }
set { option = value; }
}
string date;
public string Date
{
get { return date; }
set { date = value; }
}
}
Hope this helps
References:
Json2.js file
stringify method
define a class in js

How to redirect data to a particular page using url in c#?

I am working on jQuery fileupload now here I am saving images once saved some data I need to post to my page
Here I have two applications (two separate applications) html.page to I am posting images to mvc upload controller and I had saved the image success fully
Now to get the respose data I need to redirect through url so I am redirecting through like this
public void ReturnResult(string jsonObj)
{
var hostName = " http://localhost:8988/cors/postmessage.html?MyURL=";
var s = jsonObj;
var filterUrl = hostName + s;
HttpContext.Current.Response.Redirect(filterUrl);
}
Once redirection to this page how could I get those data?
And I don't have any idea is this redirecting the data or not how could could I know that
data is redirecting or not could u plz help me get the data
this is my
redirected to this page
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Plugin postMessage API</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
'use strict';
var origin = /^http:\/\/example.org/,
//var origin = 'http://localhost:4071/Upload/UploadHandler.ashx',
target = new RegExp('^(http(s)?:)?\\/\\/' + location.host + '\\/');
alert(1);
alert(origin);
$(window).on('message', function (e) {
e = e.originalEvent;
var s = e.data,
xhr = $.ajaxSettings.xhr(),
f;
if (!origin.test(e.origin)) {
throw new Error('Origin "' + e.origin + '" does not match ' + origin);
}
if (!target.test(e.data.url)) {
throw new Error('Target "' + e.data.url + '" does not match ' + target);
}
$(xhr.upload).on('progress', function (ev) {
ev = ev.originalEvent;
e.source.postMessage({
id: s.id,
type: ev.type,
timeStamp: ev.timeStamp,
lengthComputable: ev.lengthComputable,
loaded: ev.loaded,
total: ev.total
}, e.origin);
});
s.xhr = function () {
return xhr;
};
if (!(s.data instanceof Blob)) {
f = new FormData();
$.each(s.data, function (i, v) {
f.append(v.name, v.value);
});
s.data = f;
}
$.ajax(s).always(function (result, statusText, jqXHR) {
if (!jqXHR.done) {
jqXHR = result;
result = null;
}
e.source.postMessage({
id: s.id,
status: jqXHR.status,
statusText: statusText,
result: result,
headers: jqXHR.getAllResponseHeaders()
}, e.origin);
});
});
</script>
</body>
</html>
Any help will greately appreciated thanks in advance
If you need to get data from the query string returned from the controller in your HTML page then you can use this function.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
you can get you values on page load like:
var MyURL= getUrlVars()['MyURL'];

Retrieve JSON Array from jQuery Ajax call in asp.net webpages

I am trying to send some data through an ajax call of jQuery. My question is : how do I get hold of this JSON array in my Insert.cshtml file? I have tried Request["rows"], Request[0][rows], etc. but without any success.
Here, the data I am trying to send is this (multiple rows of form data):
[
{
"sl": "1",
"tname": "Gardening",
"ttype": "4",
"tduration": "12"
},
{
"sl": "2",
"tname": "Nursing",
"ttype": "4",
"tduration": "45"
}
]
jQuery Code:
$.ajax({
type: "POST",
url: "/Insert",
data: rows,
contentType: "application/json",
success: function (data, status) {
alert(status);
},
error: function (xhr, textStatus, error) {
var errorMessage = error || xhr.statusText;
alert(errorMessage);
}
});
Update: A partial demo in jsfiddle - http://jsfiddle.net/rafi867/gprQs/8/
I have tried to simulate your problem creating in App_Code a Sample.cs class:
public class Sample
{
public string sl { get; set; }
public string tname { get; set; }
public string ttype { get; set; }
public string tduration { get; set; }
}
Now your Insert.cshtml file should look like this:
#{
var sample = new Sample[]{
new Sample{ sl = "1", tname = "Gardening", ttype = "4", tduration = "12" },
new Sample{ sl = "2", tname = "Nursing", ttype = "4", tduration = "45" }
};
Json.Write(sample, Response.Output);
}
and the file (ReadSample.cshtml?) that holds your Sample objects should be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="~/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.getJSON('/Insert', function (sample)
{
var custList = "";
$.each(sample, function (index, obj) {
custList += "<li>" + obj.sl + " - " + obj.tname +
" - " + obj.ttype + " - " + obj.tduration + "</li>";
})
$("#list").html("<ul>" + custList + "</ul>")
})
</script>
</head>
<body>
<div id="list"></div>
</body>
</html>
In my example I have readed the objects array with
$.getJSON('/Insert', function (sample)
and created an unordered list to display its content
$.each(sample, function (index, obj) {
custList += "<li>" + obj.sl + " - " + obj.tname +
" - " + obj.ttype + " - " + obj.tduration + "</li>";
})
$("#list").html("<ul>" + custList + "</ul>")
I hope this could help.
I have put a sample code for show how to display array items on web page by using jquery and css. By using this try to understand the concept and then apply it to your scenario.
HTML
<div class="dialog" id="unpaid-dialog" data-width="550" data-title="Checkout">
<ul>
<li id="serviceAndRetailDetails" style="text-align: left;"></li>
</ul>
</div>
Jquery
<script type="text/javascript">
var toBePaidItems = new Array();//create a array
var make = "";
$.ajax({
type: "GET",
url: "/Portal/GetServiceAndRetailSalesDetails",
dataType: 'json',
contentType: "application/json; charset=UTF-8",
data: { invoiceOrSaleId: invoiceOrSaleId, providerKey: providerKey },
success: function (response) {
make = "<table id='tblPayment'>";
toBePaidItems = [];
$.each(response, function (index, sr) {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td><td></tr>";
//insert into array
toBePaidItems.push(sr.AllocationOrInvoiceOrSaleId);
});
make += "</table>";
$("#serviceAndRetailDetails").html(make);
}
});
</script>
Controller Action Method
[HttpGet]
public JsonResult GetServiceAndRetailSalesDetails(Guid invoiceOrSaleId, string providerKey)
{
var items = new List<CheckOutServiceAndRetailItem>();
var serviceDetails = Repository.GetAllPayableItems(invoiceOrSaleId).ToList();
foreach (var s in serviceDetails)
{
var item = new CheckOutServiceAndRetailItem
{
AllocationOrInvoiceOrSaleId = s.Allocation.AllocationId,
Name = s.Allocation.Service.Name,
Price = s.LatestTotal,
Class = s.Allocation.Service.IsAnExtra,
};
items.Add(item);
}
return Json(items, JsonRequestBehavior.AllowGet);
}
Array Out Put
How to manipulate Arrays Here
Hope This will help to you.
The data parameter is meant to map name-value pairs to query string parameters as you can tell by the docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
If you then go on to read the docs for the .param() method, this should help you understand what's going on with your request and how jQuery sends your object to the server.
You may just have to name your objects/arrays in your data object so you can refer to them in the Request.Forms object.

Categories

Resources