Iterate through JSON Array and show result in a HTML table - c#

I try to iterate through an array and show the results in a HTML table. The Data is coming from a webservice.
My JavaScript function:
function loadDate() {
var PanelID = document.getElementById('PanelID').value;
alert(PanelID);
$.ajax({
type: "POST",
url: "../../WebService/QRCode.asmx/getDatetime",
data: "{ 'PanelID': '" + PanelID + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: true,
success: function(data) {
var table = document.createElement('table');
var str = '<table>';
str += '<tr><th>Von</th><th>Bis</th><th>Thema</th></tr>';
for(var i = 0; i < data.d.length; i++) {
str += '<tr><td>' + data.d[i].Von + '</td><td>' + data.d[i].Bis + '</td><td>' + data.d[i].Thema + '</td></tr>';
}
str += '</table>';
return str;
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = loadDate(data);
},
error: function(x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
}
HTML Part
<body>
<h1>
Check-In und Check-Out von Besprechungen</h1>
<form id="form1" runat="server">
<div id = "DataTable"> </div>
<p>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
Raumname:
<br />
<asp:TextBox type="text" name="Panels" ID="PanelID" value="" runat="server"></asp:TextBox>
<br />
<br />
<asp:TextBox type="text" ID="Table" mode="multiline" runat="server" Coloumns="100" Rows="200"
Height="230px" Width="405px"></asp:TextBox>
<br />
<br />
<asp:Button ID="button" runat="server" Text="Check-In" Width="99px" OnClientClick="return loadDate();" />
<asp:Button ID="button1" runat="server" Text="Check_Out" Width="99px" />
</p>
</form>
</body>
The Problem is that something is not working in my code. If I do it with the above code I can't display the values.
I think it has something to do wit the for clause, because
f i change the FOR clause for example:
for(var i = 0; i < data.d.length; i++) {
var VonDatum = data.d[i].Von;
$("#Table").val(VonDatum);
}
so I can display the Von value in a textbox. But if I do it like that the FOR clause is displaying only one value, but there are more than 30 values in the array.
My JSON-Data looks like:
{"d":[{"Von":"18.05.2012 00:00:00","Bis":"18.06.2012 00:00:00","Thema":"Raum ist gesperrt","PanelIDs":"FAT-1"}]}

OLD
return str;
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = loadDate(data);
NEW
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = loadDate(data);
return str;
but your str not set in any element so you want to set element ?
like this way
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = str;

Why do you have
return str;
Where are you returning it to? Should your code be
existingDiv.innerHTML = loadDate(str);

Related

Importing data to google maps though Asp.net/C#

I build an example and made it run, but the problem is, that it only shows one of the markers instead of them both.
This is what is in my repeater.
12.545020 55.675020 , 12.388520 55.618460
My code looks like this
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
<asp:Label ID="lbl_Adresse" CssClass="LongitudeLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Longitude")%>' />
<asp:Label ID="Label1" CssClass="LatitudeLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Latitude")%>' />
<asp:Label ID="Label2" CssClass="LocationLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Adresse")%>' />
<asp:Label ID="lbl_Fornavn" CssClass="Cust_NameLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Fornavn")%>' />
<asp:Label ID="lbl_Titel" CssClass="DescriptionLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Titel")%>' />
<asp:Label ID="Label3" CssClass="BilledeLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Billede")%>' />
<asp:Label ID="Label4" CssClass="IDLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "BrugerID")%>' />
</ItemTemplate>
,
my javascript look like this
var markers = { locationLatitude: "", locationLongitude: "", Cust_Name: "", Description: "" };
var markerArray = [];
window.onload = function () {
var t = self.setTimeout(function () {
var size = $('.LocationLabel').length;
for (i = 0; i < size; i++) {
var id = $('.IDLabel').eq(i).text();
var Location = $('.LocationLabel').eq(i).text();
var CustName = $('.Cust_NameLabel').eq(i).text();
var Description = $('.DescriptionLabel').eq(i).text();
var Billede = $('.BilledeLabel').eq(i).text();
markers.locationLatitude = $('.LatitudeLabel').eq(i).text();
markers.locationLongitude = $('.LongitudeLabel').eq(i).text();
markers.Cust_Name = CustName;
markers.Description = "Navn: " + CustName + "<br />" + "Titel: " + Description + "<br />" + Billede + "<br />" + 'Se Profil';
markerArray.push(markers);
}
var mapOptions = {
center: new google.maps.LatLng(markers.locationLatitude, markers.locationLongitude),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
for (i = 0; i < markerArray.length; i++) {
var data = markerArray[i]
var myLatlng = new google.maps.LatLng(data.locationLatitude, data.locationLongitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.Cust_Name
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.Description);
infoWindow.open(map, marker);
});
})(marker, data);
}
});
}
This example works, but it dont show all the markers on the map

$.ajax is not working with ASP.NET

I'm trying to call $.ajax method to retrieve NORTHWND Employees details based on the search criteria. But, for some reason, country, and title variable are always returning null. I am not understanding where I am doing wrong.
Below is the clear explanation.
Below is the code in AjaxDemoRequestPage.aspx
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country = $("#txtCountry").val();
data.title = $("#txtTitle").val();
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
Below is the code in PostTarget.aspx.cs page. In this page, when debugging I am always getting country, and title as null.
public partial class PostTarget : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var country = Request.Form["country"];
var title = Request.Form["title"];
var db = new NORTHWNDEntities();
var emps = db.Employees
.Where(x => x.Country.Contains(country) || x.Title.Contains(title))
.Select(x => new EmployeeSearchResult
{
EmployeeID = x.EmployeeID,
FirstName = x.FirstName,
LastName = x.LastName
});
Response.Clear();
Response.Write(JsonConvert.SerializeObject(emps));
Response.Flush();
Response.End();
}
}
Can anyone please suggest me where I am doing wrong?
The contentType should be this:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
My blunder mistake was that I never made call to $.ajax method. Below is the modified and working code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
$.ajax(data);
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
ID generated by ASP.NET will not same as you have given. this is the reason you are getting null value .
You can access ASP.NET control in javascript in this way.
document.getElementById('<%= txtCountry.ClientID %>').value
And also you can simple use html button instead of ASP.NET button for making ajax request.
Here is your updated code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>

Button in asp.net web forms dont fire event

can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.

jquery function not being called by web api

I have an web api to post data in the table when data entered in html page through jquery.
The web api function is as:
public HttpResponseMessage Post(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
And the html page with jquery script is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<h2>All users</h2>
<ul id="users" />
</div>
<div>
<h2>Insert New User</h2>
First Name : <input type="text" id="firstName" /><br />
Last Name : <input type="text" id="lastName" /><br />
City : <input type="text" id="city" /><br />
Email : <input type="email" id="email" /><br />
Password : <input type="password" id="password" /><br />
Phone number: <input type="number" id="phone" /><br />
<input type="button" id="btnsave" value="Save" onclick="Post();" />
<p id="P1" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/user';
$(document).ready(function () {
// Send an AJAX request
getuserlist();
});
function getuserlist() {
$.getJSON(uri)
.done(function (data) {
$('#users').html('');
// On success, 'data' contains a list of users.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: formatItem(item) }).appendTo($('#users'));
});
});
}
function formatItem(item) {
return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
}
function Post() {
jQuery.support.cors = true;
var source = {
'firstName': $('#firstName').val(),
'lastName': $('#lastName').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'city': $('#city').val(),
'password': $('#password').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/user",
data: source,
success: function (data) {
var strResult = "<table><th>Returned Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + source.email + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
},
error: function (x, y, z) {
var strResult = "<table><th>Error Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
// alert(x + '\n' + y + '\n' + z);
}
//success: function (data) {
// //alert(data);
// getuserlist();
// // alert(jQuery.parseJSON(data));
//},
//error: function (error) {
// jsonValue = jQuery.parseJSON(error.responseText);
// //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
//}
});
});
</script>
</body>
</html>
when I click on the button to add anew user,the post() function is not working.
the page remains the same,no action,no error.
please help!
Thanks!
Firstly the url that you are posting to should be "/api/user/Post".
Output
There are several other JavaScript errors in the posted code that I had to fix. As other's have mentioned in the comments these errors were shown in the console. Knowing how to debug using the developer tools is invaluable and worth investing time to learn them.
Here is the updated code fixed:
<div>
<h2>All users</h2>
<ul id="users" />
</div>
<div>
<h2>Insert New User</h2>
First Name : <input type="text" id="firstName" /><br />
Last Name : <input type="text" id="lastName" /><br />
City : <input type="text" id="city" /><br />
Email : <input type="email" id="email" /><br />
Password : <input type="password" id="password" /><br />
Phone number: <input type="number" id="phone" /><br />
<input type="button" id="btnsave" value="Save" onclick="Post();" />
<p id="P1" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/user';
$(document).ready(function () {
// Send an AJAX request
getuserlist();
});
function getuserlist() {
$.getJSON(uri)
.done(function (data) {
$('#users').html('');
// On success, 'data' contains a list of users.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: formatItem(item) }).appendTo($('#users'));
});
});
}
function formatItem(item) {
return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
}
function Post() {
jQuery.support.cors = true;
var source = {
'firstName': $('#firstName').val(),
'lastName': $('#lastName').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'city': $('#city').val(),
'password': $('#password').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/user/Post",
data: source,
success: function (data) {
var strResult = "<table><th>Returned Message</th>";
$.each(data, function (index, data) {
strResult += "<tr><td> " + source.email + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
});
},
error: function (x, y, z) {
var strResult = "<table><th>Error Message</th>";
$.each(x, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
// alert(x + '\n' + y + '\n' + z);
});
}
//success: function (data) {
// //alert(data);
// getuserlist();
// // alert(jQuery.parseJSON(data));
//},
//error: function (error) {
// jsonValue = jQuery.parseJSON(error.responseText);
// //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
//}
});
};
</script>
I have also made the assumption that your User object is as follows:
public class User
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string city { get; set; }
public string password { get; set; }
}

dynamically add button column in Asp.net GridView using Jquery

I have populated Grid View Dynamically with json Data ..Button Column started to appears only in First Row ..But not in below rows ..
I have Tried Code to add column in server side code as well as in Mark Up ..I also search but could not able to find any thing relevant
this is my MarkUp :
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List.aspx/GetData",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].c1 + "</td><td>" + data.d[i].c2 + "</td><td>" + "</td></tr>");
}
},
error: function (result) {
alert(result.status + ' ' + result.statusText);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server" ShowHeaderWhenEmpty="True">
<Columns>
<asp:ButtonField Text="Button" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
this is code behind :
protected void Page_Load(object sender, EventArgs e)
{
BindColumnToGridview();
}
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("c1");
dt.Columns.Add("c2");
dt.Rows.Add();
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static tbl1[] GetData()
{
try
{
using (var context = new TestDBContext())
{
List<tbl1> lsTbl1 = new List<tbl1>();
lsTbl1 = (from c in context.tbl1 select c).ToList();
return lsTbl1.ToArray();
}
}
catch (Exception)
{
throw;
}
}
I also tried to add column from code behind
gvDetails.Columns.Add(new ButtonField() { Text = "Button" });
this is not working too
any sugestion will be helpful
Since gvDetails is a server side control you should use <%= gvDetails.ClientID %> in your JS snippet.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List.aspx/GetData",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#<%= gvDetails.ClientID %>").append("<tr><td>" + data.d[i].c1 + "</td><td>" + data.d[i].c2 + "</td><td>" + "</td></tr>");
}
},
error: function (result) {
alert(result.status + ' ' + result.statusText);
}
});
});
</script>
EDIT:

Categories