I am trying to deserialize JSON to C# list. I have the Jquery code as,
$(document).ready(function () {
$("#btn_check").click(function () {
var str="";
x = $("#frm").serializeArray();
$("#Label1").empty();
$.each(x, function (i, field) {
// $("#Label1").append(field.name + ":" + field.value + " ");
str = str + field.name + ":" + field.value + " ";
});
var jsonstr=JSON.stringify(str); });
});
after stringify, I get something weird as jsonstr=
__VIEWSTATE:/wEPDwUKLTg1MjI5MDU0MWQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFjIFB2NoZWNrXzAFB2NoZWNrXzEFB2NoZWNrXzIFB2NoZWNrXzMFB2NoZWNrXzQFB2NoZWNrXzUFB2NoZWNrXzYFB2NoZWNrXzcFB2NoZWNrXzgFB2NoZWNrXzkFCGNoZWNrXzEwBQhjaGVja18xMQUIY2hlY2tfMTIFCGNoZWNrXzEzBQhjaGVja18xNAUIY2hlY2tfMTUFCGNoZWNrXzE2BQhjaGVja18xNwUIY2hlY2tfMTgFCGNoZWNrXzE5BQhjaGVja18yMAUIY2hlY2tfMjEFCGNoZWNrXzIyBQhjaGVja18yMwUIY2hlY2tfMjQFCGNoZWNrXzI1BQhjaGVja18yNgUIY2hlY2tfMjcFCGNoZWNrXzI4BQhjaGVja18yOQUIY2hlY2tfMzAFCGNoZWNrXzMxBQhjaGVja18zMgUIY2hlY2tfMzMFCGNoZWNrXzM0BQhjaGVja18zNQUIY2hlY2tfMzYFCGNoZWNrXzM3BQhjaGVja18zOAUIY2hlY2tfMzkFCGNoZWNrXzQwBQhjaGVja180MQUIY2hlY2tfNDIFCGNoZWNrXzQzBQhjaGVja180NAUIY2hlY2tfNDUFCGNoZWNrXzQ2BQhjaGVja180NwUIY2hlY2tfNDgFCGNoZWNrXzQ5s98N0sYArkR3uk7Sb4bJWOocOpU= __VIEWSTATEGENERATOR:172284EE __EVENTVALIDATION:/wEWNAKauo6nDAK5rJ0YAp7D/4IGAoPa4e0LAujww9gBAs2HpsMHArKeiK4NApe16pgDAvzLzIMJApH2i8IBAvaM7qwHAp7Dv7UBAp7Dq9oIAp7Dl/8PAp7Dg6QHAp7Dj6IEAp7D+8YLAp7D5+sCAp7D05AKAp7Dn9wLAp7Di4EDAoPaoaAHAoPajcUOAoPa+ekFAoPa5Y4NAoPa8YwKAoPa3bEBAoPaydYIAoPatfsPAoPagccBAoPa7esIAujwg4sNAujw768EAujw29QLAujwx/kCAujw0/cPAujwv5wHAujwq8EOAujwl+YFAujw47EHAujwz9YOAs2H5vUCAs2H0poKAs2Hvr8BAs2HquQIAs2HtuIFAs2HoocNAs2HjqwEAs2H+tALAs2HxpwNAs2HssEEAvCFnqIPppJbhAvF8AzSoMd/uZfiRXpzWu0= check_0:on check_1:on check_2:on check_3:on check_4:on check_5:on check_6:on check_7:on check_8:on check_9:on check_10:on check_11:on check_12:on check_13:on check_14:on check_15:on check_16:on check_17:on check_18:on check_19:on check_20:on check_21:on check_22:on check_23:on check_24:on check_25:on check_26:on check_27:on check_28:on check_29:on check_30:on check_31:on check_32:on check_33:on check_34:on check_35:on check_36:on check_37:on check_38:on check_39:on check_40:on check_41:on check_42:on check_43:on check_44:on check_45:on check_46:on check_47:on check_48:on check_49:on
check_0 to check_1 are the dynamically created checkboxes and I want to get their values in C# as list or in any form to interpret and push them into Database.
asp.net:
<form id="frm" runat="server">
<asp:Panel ID="pnl_seat" runat="server">
<asp:PlaceHolder ID="plhdr_seat" runat="server">
checkboxes are dynamically created here
</asp:PlaceHolder>
<br />
<button id="btn_check" type="button">Serialize form values</button>
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
</asp:Panel>
</form>
picture:
C# code:
using Newtonsoft.Json;
class abc // some class
{
protected void btn_submit_Click(object sender, EventArgs e)
{
List<Test> myDeserializedObjList = (List<Test>) Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonstr"], typeof(List<Test>));
}
}
the above code I got it from codeproject.com.
But on running this code, I am getting an exception that "str" as "null". How to push the label1 or str to server side? Help me please.
Could you paste more code? It's hard to find any issues from the limited source code.
You may send the str to server using an ajax request:
$.get('your url', {str: str})
By the way, It seems the str is not a valid JSON string. str = JSON.strigify(x) will stringify the object to a JSON string.
Try this:
```
$(document).ready(function () {
$("#btn_check").click(function () {
var x = $("#frm").serializeArray();
$("#Label1").empty().text(JSON.stringify(x));
});
});
using Newtonsoft.Json;
class abc // some class
{
protected void btn_submit_Click(object sender, EventArgs e)
{
List<Test> myDeserializedObjList = (List<Test>) Newtonsoft.Json.JsonConvert.DeserializeObject(Label1.Text, typeof(List<Test>));
}
}
```
JQUERY:
$(document).ready(function () {
$("#btn_check").click(function () {
var str = "";
x = $("#frm").serializeArray();
str = JSON.stringify(x);
// $("#HiddenField1").Value(str);
$('#<%=hdnSelectedTicket.ClientID %>').val(str);
<%-- $('#<%=hdnSelectedTicket.ClientID %>')--%>
});
});
ASP.NET:
<form id="frm" runat="server">
<asp:HiddenField ID="hdnSelectedTicket" runat="server" />
<asp:Panel ID="pnl_seat" runat="server">
<asp:PlaceHolder ID="plhdr_seat" runat="server"></asp:PlaceHolder>
<br />
<button id="btn_check" type="button">Serialize form values</button>
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
</asp:Panel>
</form>
C#:
using Newtonsoft.Json;
protected void btn_submit_Click(object sender, EventArgs e)
{
//string a = hdnSelectedTicket.Value;
List<Test> myDeserializedObjList = (List<Test>)Newtonsoft.Json.JsonConvert.DeserializeObject (hdnSelectedTicket.Value, typeof(List<Test>));
}
Related
In my ASP.Net app, I have a button that launches a modal. The onClick event fires the C# behind code that launches a modal. I am then calling a data table and populating string variables with values from the data table:
protected void uxTicketHistoryButton_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "key", "launchModal();", true);
DataTable ticketHist = _dtMgr.GetContactInfoByName(uxContactDropdownList.SelectedValue);
string rName = ticketHist.Rows[0]["RequestorName"].ToString();
string rPhone = ticketHist.Rows[0]["RequestorPhone"].ToString();
string rPhoneExt = ticketHist.Rows[0]["RequestorPhoneExt"].ToString();
string rEmail = ticketHist.Rows[0]["RequestorEmail"].ToString(); ;
string rState = ticketHist.Rows[0]["RequestorState"].ToString();
string rOrg = ticketHist.Rows[0]["RequestorOrg"].ToString();
}
What I want to do now is add those variable values to my modal inside the panel.
<asp:Button ID="uxTicketHistoryButton" runat="server" Text="Show Ticket History" style="color: blue;" OnClick="uxTicketHistoryButton_Click"/>
<!-- ModalPopupExtender-->
<ajaxToolkit:ModalPopupExtender ID="uxTicketHistoryModal" runat="server" PopupControlID="Panel1" TargetControlID="uxTicketHistoryButton"CancelControlID="btnClose" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" style = "display:none">
**** Add variable values here ****
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
How do I add the variables from my .cs file to the modal panel in my .aspx file so that it shows up like this (values in the { } )?
UPDATE
This issue seems to be related to the modal interfering with the _Click event function of my button. I have posted an additional question to resolve this problem first. Then, I believe one of the solutions below may work. Thanks everybody!
Webform:
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" style = "display:none">
Name: <asp:Literal ID="Name" runat="server" /><br>
Organization: <asp:Literal ID="Organization" runat="server" /><br>
etc....
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
Codebehind:
Name.Text = ticketHist.Rows[0]["RequestorName"].ToString();
Organization.Text = ticketHist.Rows[0]["RequestorOrg"].ToString()
You can use ASP.NET Razor to post your c# variables directly into your html.
For Example
<!-- Single statement block -->
#{ var myMessage = "Hello World"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: #myMessage</p>
<!-- Multi-statement block -->
#{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: #greetingMessage</p>
OR
you could use get and set methods to post your variables to the modal from you .cs .
public class yourModalPage
{
public string RequestorName { get; set; }
}
Then you can send values to your modal from your .cs with
yourModalPage.RequestorName = "RequestorName";
i am trying to learn classes and objects in C#, i want to get the textbox value and show it in a label using classes and get set property.
i try the below process, but i will not showing/output anything.
index.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="classes.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="fname" runat="server" /><br />
<asp:TextBox ID="lname" runat="server" /><br />
<asp:TextBox ID="password" runat="server" /><br />
<asp:Button Text="Submit" ID="submit" runat="server" OnClick="submit_Click" />
<br />
<br />
<br />
<br />
<asp:Label ID="FirstName" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Button click code
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
FirstName.Text = bn.fname;
}
class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace classes
{
public class basicinfo
{
public string fname;
public string last_name;
public string password;
public string Name
{
get{return fname;}
set{fname=value;}
}
}
}
Can someone tell me is this the wrong way? Also please provide reference of any helping material/Links/video tutorials course through which i can clear my basic classes, get set, objects, methods idea, i am heaving trouble to understand it.
Update
if this how it works
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
bn.Name = fname.Text;
FirstName.Text =bn.Name;
}
then why should we use classes and get, set properties?
we can simply do like
protected void submit_Click(object sender, EventArgs e)
{
FirstName.Text = fname.Text;
}
You are trying to save the object value in the Label but Your object is empty it does not contain textbox value. Your code should be
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
bn.fname= fname.Text; //textbox value to object
FirstName.Text = bn.fname; //object value to label
}
I have 2 textboxes turn into jquery datepickers and some folder names like 09-13-2014, 09-14-2014 and 09-15-2014, how can I get all folder names from the selected dates on button click and place it on a treeview? I'm new to this, not yet familliar on the back end coding.
Here's my datepickers:
<script type="text/javascript">
$(function () {
$("[id$=txtDate1]").datepicker({
dateFormat: 'mm-dd-yy',
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'Images/calendar.png'
});
});
</script>
<p>
From: <asp:TextBox ID="txtDate1" runat="server" ReadOnly = "true"></asp:TextBox>
To:<asp:TextBox ID="txtDate2" runat="server" ReadOnly = "true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" />
</p>
I supposed that you datepicker working fine and it showing the calender.
<p>
From:
//you should delete ReadOnly = "true" on textboxes
<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>
To:<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
</p>
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
on code behinde write this codes. you can go to codebehind by rightclick on your page and then selecting view code.
protected void Button1_Click(object sender, EventArgs e)
{
var start = Convert.ToDateTime(txtDate1.Text);
var end = Convert.ToDateTime(txtDate2.Text);
if (end < start)
return;
var folderNamelst = GetListOfExsistingFolderName(start, end);
AddNodes(folderNamelst);
}
private IEnumerable<string> GetListOfExsistingFolderName(DateTime startDate, DateTime endTime)
{
var mainFolderPath = Server.MapPath("~/Folders");
var folderNamelst = new List<string>();
var day = startDate;
do
{
if (Directory.Exists(mainFolderPath + "\\" + day.ToString("MM-dd-yyyy")))
folderNamelst.Add(day.ToString("MM-dd-yyyy"));
day = day.AddDays(1);
} while (day <= endTime);
return folderNamelst;
}
private void AddNodes(IEnumerable<string> data)
{
TreeView1.Nodes.Clear();
var root = new TreeNode("Folders");
foreach (var d in data)
{
var treechild = new TreeNode(d);
root.ChildNodes.Add(treechild);
}
TreeView1.Nodes.Add(root);
}
I have this function on aspx(html)
<body onload="NewPage2()">
<script type="text/javascript">
function NewPage2() {
var url = getUrlVars(url);
document.getElementById("HiddenField1").Value = url["access_token"];
}
</script>
<div class = content>
<form id="form1" runat="server">
<asp:HiddenField id="HiddenField1" runat="server" Value=""/>
</form>
CODE1: <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000" />
</div>
</div>
</body>
how can I get the var(on jquery(html)) to my variableURL2 in aspx.cs?
protected void Page_Load(object sender, EventArgs e)
{
string code = HiddenField1.Value;
Label1.Text = code;
saveToken(token, code);
}
Have one server hidden control in .aspx page
<asp:HiddenField Id="HiddenField1" runat="server"></asp:HiddenField>
in browser it will be rendered like this
<input type="hidden" id="HiddenField1" />
assign values from javascript
document.getElementById("HiddenField1").value = "your values here";
in aspx.cs render like this
string variableURL2 = HiddenField1.Value;
There are two ways you can do this, and both would have to be from a post back since the javascript is fired after the page loads.
redirect and append to the query string, then read it from c#
javascript:
location.href = "/mypage.aspx?variable2=VARFROMJAVASCRIPT";
c#
string variable2 = Request.QueryString["variable2"];
or set the value to a hidden field like above
javascript:
var $hiddenInput = $('',{type:'hidden',id:'variable2',value:'VARFROMJAVASCRIPT'});
$hiddenInput.appendTo('body');
c#
string variable2 = Request["variable2"];
.aspx:
<asp:HiddenField id="HiddenField1" runat="server" value=""/>
javascript:
function end(url) {
var url = getUrlVars(url);
var url2 = url["access_token"];
document..getElementById("HiddenField1").value = url2;
}
.cs file:
string variableURL2 = HiddenField1.Value;
Use server control HiddenField
First you have to add control in your aspx/ascx/master file
<asp:HiddenFiled ID="hdn" runat="server"/>
Then you can use this control in JS
function end(url) {
var url = getUrlVars(url);
var url2 = url["access_token"];
<%= hdn.ClientId %>.value = url["access_token"];
}
in code behind
protected void Page_Load(object sender, EventArgs e)
{
string variableURL2 = hdn.Value;
}
I have two labels:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
and I set innerHTML by javascript:
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
How I can get those labels values in codebehind? I try:
TextBox2.Text = Label1.Text;
UPDATE:I need to get pushpin location:
<artem:GoogleMap ID="GoogleMap1" runat="server"
EnableMapTypeControl="False" MapType="Roadmap" >
</artem:GoogleMap>
<artem:GoogleMarkers ID="GoogleMarkers1" runat="server"
TargetControlID="GoogleMap1" onclientpositionchanged="handlePositionChanged">
</artem:GoogleMarkers>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<script type="text/javascript">
var list = document.getElementById("Label1");
function handlePositionChanged(sender, e) {
printEvent("Position Changed", sender, e);
}
function printEvent(name, sender, e) {
var position = e.latLng || sender.markers[e.index].getPosition();
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
}
</script>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox2.Text = Label1.Text;// return value: Label
}
You cannot access the value on server side. You will have to use a hidden field for that:
<asp:HiddenField ID="Hidden1" runat="server" />
The set the innerHtml value in the Hidden field by doing:
document.getElementById('<%= Hidden1.ClientID %>').value = position.lat();
You can then access it from server side by doing:
TextBox1.Text = Hidden1.Value;
You are not able to do that with the Label control as when the page is posted back the content of labels are not posted to the server. You would need to make use of an input control of sorts. Probably a hidden input would be your best bet.
Take a hidden field like below
<asp:HiddenField ID="hdnBody" ClientIDMode="Static" runat="server" />
Then set its value in Jquery like below
<script>
function GetEmailID() {
var bodyHtml = $("#editor").html();
$("#hdnBody").val(bodyHtml);
}
</script>
And in the code behind do this to get it
string body = hdnBody.Value;