I trying to add HTML or image button which can call code behind method, from a static method(Web method), I am calling web method through AJAX. My code is:
AJAX Method
function dispData()
{
var text_data = document.getElementById("TextBox1").value;
var text_count = text_data.length;
if (text_count >= 4)
{
alert("Text box val = " + text_data + " :Count = " + text_count);
$.ajax({
type: "POST",
url: "WebForm2.aspx/ajaxData",
data: JSON.stringify({ data: text_data }),
contentType: 'application/json; charset=utf-8',
dataType: "JSON",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
//alert("We returned: " + result.d);
$('#disp_ajax_data').html(result.d);<-- displaying result in div
}
})
return false;//end of ajax
}//end of if text_count.
}//end of dispData.
[WebMethod(TransactionOption = TransactionOption.Supported)]
public static string ajaxData(string data)
{
for (int loopCount = 0; loopCount < myCount; loopCount++)
{
string ele = oCompInfoSet[loopCount].Name + "<a href='codeBehindMethod()'>Add</a>" + "<br>";
returnVal += ele;
}//end for loop.
}
I am displaying the names properly but not able to get the buttons. Can anyone please help
EDIT:
From deostroll's help, my changed code, Oh... silly me.... I missed 'Static' keyword. I am trying to pass value now
for (int loopCount = 0; loopCount < oCompInfoSet.ComponentCount; loopCount++)
{
//Debug.WriteLine("In for loop");
string ele_name = oCompInfoSet[loopCount].Component.Name;
string ele = ele_name + "<a href='#' OnClick='add_ele("+ele_name+")'>Add</a> <br>";
returnVal += ele;
}//end for loop.
[WebMethod(TransactionOption = TransactionOption.Supported)]
public static void addToStream()
{
Debug.WriteLine("Add to stream here");
}//end of addToStream
JS METHOD:
function add_ele(name)
{
alert("add ele called, "+name);
//PageMethods.addToStream();
}//end of add_ele.
I am not getting alert also now, getting "Unidentified Error"....
Try looking at this: http://visualstudiomagazine.com/articles/2007/08/28/creating-and-consuming-aspnet-ajax-page-methods.aspx
The article above utilizes a concept called Page Methods. You have to enable it on the ScriptManager. Here is a simple example that is kind of in line with what you are doing:
Aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.PageMethods.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page Methods</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>
<div>
<input type="button" onclick="GenerateLinks(5)" value="Add Links" />
<div id="links"></div>
<ul id="result">
</ul>
</div>
</form>
<script>
/*
*
* to generate guid
*
*/
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function GetTime() {
var g = guid();
log('sent request for ' + g);
PageMethods.GetTime(g, GetTimeSuccess);
}
function GetTimeSuccess(result) {
log('result:' + result);
}
function GenerateLinks(n) {
log('Generating links');
PageMethods.GenerateLinks(n, function (result) {
document.getElementById('links').innerHTML = result;
log('added links');
});
}
function log(msg) {
var dt = new Date();
var format = function(number){
return number < 10 ? '0' + number : number
};
var h = format(dt.getHours());
var m = format(dt.getMinutes());
var s = format(dt.getMinutes());
var ul = document.getElementById('result');
var li = document.createElement('li');
li.innerHTML = h + ':' + m + ':' + s + ' - ' + msg;
ul.appendChild(li);
}
</script>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Web.Services;
namespace WebApp.PageMethods
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GenerateLinks(int number)
{
List<string> a = new List<string>();
for (int i = 0; i < number; i++)
{
a.Add("Get Time " + (i + 1) + "");
}
return string.Join("<br/>", a);
}
[WebMethod]
public static string GetTime(string guid)
{
return guid + " / " + DateTime.Now.ToLongTimeString();
}
}
}
Related
I am adding some html/css in div.InnerHtml by applying foreach loop reading each directory contents to post images, and i want to call function showfile(dynamic parameter) into it.
how should i do this?
the showfiles(dynamic parameter) function is working fine, but i want to make it work after user clicks the controls generated in div, which is not working, please have a look on my code and give me suggestion.
public void Showimages( string fname)
{
string name = Path.GetFileName(fname); //select only name.ext
str2 = "<div style='max-width:250px; max-height:170px;'>"
+ "<a href ='" + filepath2 + "/" + name + "' >"
+ "<img class='img-responsive' src='" + filepath2 + "/" + name + "'>"+name+"</a></div>"; //post image + name in loop
imgcontainer.InnerHtml += str2;
}
public void Generatecontrol(string dp)
{
//linkdiv.InnerHtml += "<asp:LinkButton runat='server' class='linkb' OnClick='Showfiles(" + dp.ToString()+ ")' >" + dp.ToString() + "</asp:LinkButton><br />";
linkdiv.InnerHtml += "<span class='col-lg-4'><asp:LinkButton runat='server' class='col-lg-4 linkb' OnClick='Showfiles' CommandArgument=" + dp.ToString()+ " ><img src='/pimages/folder.jpg' height='75' width='75' border='0'/><br />" + dp.ToString() + "<br /></asp:LinkButton></span>";
}
See you are passing the value as CommandArgument, so you have to take the same from CommandArgument. Change the signature of Showimages like the following:
public void Showimages(object sender, CommandEventArgs e)
{
string name = Path.GetFileName(e.CommandArgument.ToString());
// your code here
}
Pritesh,
If your main concern is only displaying images dynamically, then you can use jquery, here below I prepared a small snippet, please look at once,
Backend code:
public List<string> GetImages()
{
string fileName = "";
string[] files = System.IO.Directory.GetFiles("");
List<string> listImages = new List<string>();
foreach (string file in files)
{
fileName = System.IO.Path.GetFileName(file);
listImages.Add(fileName);
}
return listImages;
}
HTML:
<div class="row" style="margin-top:20px;">
<div id="imgPreview"></div>
</div>
<button id="btnShowImage" onclick="ShowImages()">Show Image</button>
Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function ShowImages() {
$("#imgPreview").html("");
$.ajax({
type: 'post',
url: '/xyz/GetImages',
data: formData,
success: function (response) {
if (response != null) {
var imageList =DisplayImages(response);
$("#imgPreview").append(imageList);
}
},
processData: false,
contentType: false,
error: function () {
alert("Whoops something went wrong!");
}
});
}
)};
function DisplayImages(data) {
var imageDiv ="";
if (data != null) {
$.each(data, function (index, value) {
//This is for dynamically generating image div. You can manipulate this section as per you need.
imageDiv = "<div style='max-width:250px; max-height:170px;'>";
imageDiv += "<a href ='~/your static path/" + value + "' >";
imageDiv += "<img class='img-responsive' src='='~/your static path/" + value + "'>" + value + "</a></div>";
});
}
return imageDiv;
}
</script>
Let me know if it helped.
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
I have a calender control and on selecting a respective date, I need to display Today's Due and Over due as two section in an accordion. I have written the div for accordion in code behind and set style.css to give the look of Accordion. The data from code behind is converted into json and displayed. The code behind is as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CalenderBinderAccordian()
{
try
{
//Code to fetch productGroup is not shown
foreach (var p in productGroup)
{
var todoCount = 1;
string todoString = "";
int uniqueID = Guid.NewGuid().GetHashCode();
todoString = "<div class='accordion vertical'><section id='" + uniqueID + "' style='overflow-y: scroll;'> <h2><b>Due Today</b></h2>";
foreach (var t in p.todo)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='www.google.com' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
}
todoString += "</section>";
var overDue = temps.Select(x => new { x.DueDate }).Distinct().ToList();
int overDueCount = 0;
uniqueID = Guid.NewGuid().GetHashCode();
todoString += "<section id='" + uniqueID + "'> <h2><b>Over Due</b></h2>";
int todoCount1 = 1;
for (int i = 0; i < overDue.Count(); i++)
{
if ((Convert.ToDateTime(overDue[i].DueDate) - Convert.ToDateTime(p.dates)).Days < 0)
{
overDueCount++;
var overDueList = temps.FindAll(x => x.DueDate.Equals(overDue[i].DueDate)).ToList();
foreach (var t in overDueList)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
//Error occurs when the href is given as aspx
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount1.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='PaymentDetails.aspx' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
todoCount1++;
}
}
}
todoString = todoString + "</section></div>\",\"count\":\"" + todoCount + "\"},";
jsonString = jsonString + String.Format("{{\"{0}\" : \"{1}\",\"{2}\" : \"{3}", "dates", p.dates, "todo", todoString);
if (overDueCount.Equals(0))
{
jsonString = jsonString.Replace("</section><section id='" + uniqueID + "'> <h2><b>Over Due</b></h2></section>", "</section>");
}
}
jsonString = jsonString.TrimEnd(',');
jsonString = '[' + jsonString + ']';
string data= jsonString; JavaScriptSerializer().Serialize(productGroup);
return data;
}
catch (Exception ex)
{
throw;
}
}
//How to data is converted to Jsonvar tododate = [];
$(window).bind('loaded', function () {
$.ajax({
type: "POST",
url: "ChartBinder.asmx/CalenderBinderAccordian",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
tododate = JSON.parse(msg.d);
},
error: function (msg) {
alert("error");
}
});
});
Kindly note when the href is given as www.google.com the functionality works well but when it is given as PaymentGateway.aspx It does not display date in accordion format rather shows error alert.
Using Firebug, Noticed the following Error:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
Solution: Tried changing the configuration :
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
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.
Nothing happaned when i try do this in release mode but in debug mode all work fine - why???
When i adding button and outputing data by clicking this buton.My inner links in my list rows work fine also ( http://clip2net.com/s/2AG04 ).And only on $(document).ready(function () { event this doesn't want to work...
On client i have:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index", "Product")',
cache: false,
type: 'GET',
dataType: 'json',
proccessData: false,
contentType: 'application/json; charset=utf-8'
});
On server i have this:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//Отправляем на клиент данные
_senderHub.SendMessage();
return null;
}
return View();
}
Also on server:(SignalR)
readonly ManagerDB _managerDB = new ManagerDB();
public void SendMessage()
{
IEnumerable<ProductModels> list = _managerDB.GetListOfProduct1();
var listToClient = new List<ProductModels>();
foreach (var prod in list)
{
listToClient.Add(new ProductModels
{
Id = prod.Id,
Name = prod.Name,
LockType = prod.LockType,
LockTime = prod.LockTime,
LockUser = prod.LockUser,
TimeStampF = prod.TimeStampF
});
}
var anonimProduct = listToClient;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SenderHub>();
context.Clients.AddListRows(anonimProduct);
}
On client(SignalR) trying catch this data:
$(function () {
var senderHub = $.connection.senderHub;
senderHub.AddListRows = function (data) {
var dataFromServer = data;
var listOfData = "";
for (var i = 0; i < dataFromServer.length; i++) {
$("#ListOfProductsTableBody").html(null);
var userId = '';
if (dataFromServer[i].LockUser != null) {
userId = dataFromServer[i].LockUser;
}
listOfData += ("<tr><td>" + dataFromServer[i].Id + "</td><td>" + dataFromServer[i].Name + "</td><td>" + userId + "</td><td>" + dataFromServer[i].LockType + "</td>" + "<td id=\"ModifyBlock\"><a id=\"Detail\" href=\"#\" alt=" + dataFromServer[i].Id + " >Детально</a>|<a id=\"Delete\" href=\"#\" alt=" + dataFromServer[i].Id + " >Удалить</a>|<a id=\"Edit\" href=\"#\" class=\"" + dataFromServer[i].LockTime + "\" alt=" + dataFromServer[i].Id + " >Редактировать</a></td></td></tr>");
}
$("#ListOfProductsTableBody").append(listOfData);
};
$.connection.hub.start();
});
emphasized text
See David Fowler's response to my question. Looks like you have the same issue.
Server to client messages not going through with SignalR in ASP.NET MVC 4