Generating asp controls with mark up in db [duplicate] - c#

How do I generate the controls in a div based on the markup defined in a SQL Server database? Is it possible? If yes, then how? Can anyone give me resources?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" ClientIDMode="Static" Mode="Transform"></asp:Literal>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection _newConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand storedProcedure = new SqlCommand("sp_getMarkup", _newConnection);
storedProcedure.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(storedProcedure);
_newConnection.Open();
da.Fill(ds);
_newConnection.Close();
DataTable dt = ds.Tables["Table"];
string s = (from str in dt.AsEnumerable()
where str.Field<int>("Id").Equals(1)
select str.Field<string>("elemMarkup")).SingleOrDefault().ToString();
this.lit.Text = s;
}
}
}
In the database I have stored string as
<asp:CheckBox ID="chk" runat="server" ClientIDMode="Static" />
Now the problem is the control is rendered on page but is not visible. I can see it in view source.
Can anyone help me?

You can use ParseControl which accepts a string and create controls on the fly.
The drawback is if server code is in the string, it will not be executed. In addition, you need to attach event manually such as button click events.
For example,
<script runat="server">
// This server code will not be executed
</script>

Here is another SO question using jquery ajax to load info from database
I would recommend having some type of sanitizing intermediary; otherwise you are opening yourself up to cross-site scripting (XSS) issues.

You could use a placeholder on a page like so:
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
And in your code behind, you could have several checks (all of which contain SQL statements querying the data in the database). The database could contain a field containing component names such as checkbox, button (various other controls). This saves you storing markup in the database fields..
Very rough representation of how the code would look like..
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Code here
// Datatable code here
// End of DataTable code
// Beginning of IF blocks
If (DataTable.Rows.Count > 0) {
If (your check != "checkbox") {
this.PlaceHolder1.Controls.Add(new Button(){
Text = "Added"}
}
}
// More if statements here
);
}
}
Alternatively if you insist on storing asp markup in the database, then you could just feed the asp markup into the placeholder using a loop (if there are more than one rows in your database)

Related

Crystal Report on ASP C# application & postback issues

I have a webform with a single button and one crystal report viewer. Crystal report is based on a MS SQL stored procedure & designed using a connection that uses SQL Server authentication.
What I have noticed that, if I call the method for showing the report within the page load, my crystal repot loads perfectly. However, if I trigger the report load through the button click (Which is a must for me to accept parameters for the report at deployment) the below happens:
Crystal report parameters are prompted (Which doesn't occur when report is loaded without a postback).
After the 1st page being loaded, 2nd page navigation prompts for database login. Without providing the login details (usually the password only), cannot go ahead. This logon prompt is only applicable to 2nd page of the report.
To circumvent the situation, I created a new connection with integrated security & postback stopped asking for the parameters and database login. Unfortunately, I cannot use integrated security for deploying the application & pry for a proper solution or workaround.
Fearing the worst, I already have RDLC report designed with the same requirements, however, I see that I have better formatting options like drawing lines over the sub reports to split columns when Crystal Report is used.
Here is what I have I tried until now
ASP page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="c2.aspx.cs" Inherits="CrystalTest.c2" %>
<%# Register Assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Show Report" OnClick="Button1_Click" />
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="False" GroupTreeImagesFolderUrl="" Height="1202px" ReportSourceID="CrystalReportSource1" ToolbarImagesFolderUrl="" ToolPanelView="None" ToolPanelWidth="200px" Width="1104px" />
</div>
</form>
</body>
</html>
Code behind
using CrystalDecisions.CrystalReports.Engine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CrystalTest
{
public partial class c2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//ShowReport();
}
private void ShowReport()
{
ReportDocument oRpt = new ReportDocument();
oRpt.Load(Server.MapPath(#"~/CrystalReport2.rpt"));
oRpt.SetParameterValue(0, 2020);
oRpt.SetParameterValue(1, 1);
oRpt.SetParameterValue(2, "3");
oRpt.SetParameterValue(3, "1");
oRpt.SetParameterValue(4, "1");
CrystalReportViewer1.Visible = true;
CrystalReportViewer1.ReportSource = oRpt;
//oRpt.SetDatabaseLogon("sa", "password", "RT04", "menass");
oRpt.DataSourceConnections[0].SetConnection("RT04", "menass", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
ShowReport();
}
}
}
I have referred the following threads from different websites and was able develop a simple solution.
1.https://www.c-sharpcorner.com/forums/crystal-reports-asking-for-database-login-credentials
2.https://forums.asp.net/post/1797759.aspx
All I needed was to pass the logon information back to the report viewer once after POSTBACK happens. Example as below:
ASP Page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="c3.aspx.cs" Inherits="CrystalTest.c3" %>
<%# Register Assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Print Button" OnClick="Button1_Click" />
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="false" />
</div>
</form>
</body>
</html>
Code Behind
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CrystalTest
{
public partial class c3 : System.Web.UI.Page
{
public ReportDocument oRpt;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
ConnectionInfo myConnectionInfo = new ConnectionInfo();
myConnectionInfo.ServerName = "RT04";
myConnectionInfo.DatabaseName = "MenaSS";
myConnectionInfo.UserID = "sa";
myConnectionInfo.Password = "password";
SetdblogonforReport(myConnectionInfo);
}
}
private void SetdblogonforReport(ConnectionInfo myConnectionInfo)
{
//throw new NotImplementedException
TableLogOnInfos mytableloginfos = new TableLogOnInfos();
mytableloginfos = CrystalReportViewer1.LogOnInfo;
foreach (TableLogOnInfo myTableLogOnInfo in mytableloginfos)
{
myTableLogOnInfo.ConnectionInfo = myConnectionInfo;
}
}
private void ShowReport()
{
if (!IsPostBack | Session["Report"] == (default))
{
oRpt = new ReportDocument();
oRpt.Load(Server.MapPath(#"~/CrystalReport2.rpt"));
oRpt.SetParameterValue(0, 2020);
oRpt.SetParameterValue(1, 1);
oRpt.SetParameterValue(2, "9");
oRpt.SetParameterValue(3, "1");
oRpt.SetParameterValue(4, "1");
Session.Add("Report", oRpt);
}
else
{
oRpt = (ReportDocument)Session["Report"];
}
CrystalReportViewer1.ReportSource = oRpt;
oRpt.SetDatabaseLogon("sa", "password", "RT04", "menass");
}
protected void Button1_Click(object sender, EventArgs e)
{
ShowReport();
}
}
}
This solution is good enough for sub reports also, as all the authentications are taken care by the single logon call using the method SetdblogonforReport.
Hope this helps few others out there.
I've a better solution & not deleting the previous one because it does deal with the postback when page_load method is present in a page. The below answer (which is recommended by SAP) is the one I am currently using for my project.
Resolving this requirement using "Session" and "page_init" as suggested. Please note, my application need to collect many inputs from the end user before generating the report & many of the text inputs have Autopostback set as true. Everytime the autopostback happens, Crystal Report refreshes, hence I recommend using as less possible Autopostback enabled input fields with your web form.
Sample ASP page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="c4.aspx.cs" Inherits="CrystalTest.c4" %>
<%# Register Assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Print Report" OnClick="Button1_Click" />
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
</div>
</form>
</body>
</html>
and the code behind (copied from a crude test form, please make sure that you follow the coding standards recommended). Please note, this sample doesn't have "page_load" method, hence if you have specific situations where page_load is required, you will have to adapt much tedious approaches or clicking the button to generate the report should be redirected to a page where you have only the report.
using CrystalDecisions.CrystalReports.Engine;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CrystalTest
{
public partial class c4 : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
CrystalReportViewer1.ReportSource = (ReportDocument)Session["Report"];
}
}
private void ShowReport1()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["menass"].ToString();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("GETMONTHSALARY", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#pProcessYear", SqlDbType.Int).Value = 2020;
cmd.Parameters.Add("#pProcessMonth", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("#pProcessSection", SqlDbType.VarChar).Value = "9";
cmd.Parameters.Add("#pProcessSite", SqlDbType.VarChar).Value = "1";
cmd.Parameters.Add("#pProcessCatg", SqlDbType.VarChar).Value = "1";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "SalaryDT");
ReportDocument oRpt = new ReportDocument();
oRpt.Load(Server.MapPath(#"~/dataset/CrystalReport1.rpt"));
oRpt.DataSourceConnections.Clear();
oRpt.SetDataSource(ds);
oRpt.Subreports[0].SetDataSource(FillOverTime());
CrystalReportViewer1.Visible = true;
CrystalReportViewer1.ReportSource = oRpt;
Session["Report"] = oRpt;
}
}
}
private DataSet FillOverTime()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["menass"].ToString();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("GetEmployeeOverTime", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#pEmployeeCode", SqlDbType.VarChar).Value = DBNull.Value;
cmd.Parameters.Add("#pProcessYear", SqlDbType.Int).Value = 2020;
cmd.Parameters.Add("#pProcessMonth", SqlDbType.Int).Value = 1;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
adapter.Fill(ds1, "OverTimeDT");
return ds1;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ShowReport1();
}
}
}

How to generate asp.net control using markup in database

How do I generate the controls in a div based on the markup defined in a SQL Server database? Is it possible? If yes, then how? Can anyone give me resources?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="lit" runat="server" ClientIDMode="Static" Mode="Transform"></asp:Literal>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection _newConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand storedProcedure = new SqlCommand("sp_getMarkup", _newConnection);
storedProcedure.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(storedProcedure);
_newConnection.Open();
da.Fill(ds);
_newConnection.Close();
DataTable dt = ds.Tables["Table"];
string s = (from str in dt.AsEnumerable()
where str.Field<int>("Id").Equals(1)
select str.Field<string>("elemMarkup")).SingleOrDefault().ToString();
this.lit.Text = s;
}
}
}
In the database I have stored string as
<asp:CheckBox ID="chk" runat="server" ClientIDMode="Static" />
Now the problem is the control is rendered on page but is not visible. I can see it in view source.
Can anyone help me?
You can use ParseControl which accepts a string and create controls on the fly.
The drawback is if server code is in the string, it will not be executed. In addition, you need to attach event manually such as button click events.
For example,
<script runat="server">
// This server code will not be executed
</script>
Here is another SO question using jquery ajax to load info from database
I would recommend having some type of sanitizing intermediary; otherwise you are opening yourself up to cross-site scripting (XSS) issues.
You could use a placeholder on a page like so:
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
And in your code behind, you could have several checks (all of which contain SQL statements querying the data in the database). The database could contain a field containing component names such as checkbox, button (various other controls). This saves you storing markup in the database fields..
Very rough representation of how the code would look like..
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Code here
// Datatable code here
// End of DataTable code
// Beginning of IF blocks
If (DataTable.Rows.Count > 0) {
If (your check != "checkbox") {
this.PlaceHolder1.Controls.Add(new Button(){
Text = "Added"}
}
}
// More if statements here
);
}
}
Alternatively if you insist on storing asp markup in the database, then you could just feed the asp markup into the placeholder using a loop (if there are more than one rows in your database)

Create ASP.NET page with CodeBehind Dynamically

I'd like to create a simple
default.aspx
default.aspx.cs
page dyamically and store it on the server.
I've used StreamWriter to create the directory and both files
The default.aspx I create doesn't access the codebehind.
private string displayPage = #"<%# Page Language=""C#"" AutoEventWireup=""true"" CodeBehind=""Default.aspx.cs"" %>
<!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 runat=""server"">
<title></title>
</head>
<body>
<form id=""form1"" runat=""server"">
<div>
<asp:Label id=""_lblBody"" runat=""server"" />
<asp:Label id=""_lblFooter"" runat=""server"" />
</div>
</form>
</body>
</html>";
private string codeBehindPage = #"using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
_lblBody.Text = ""Hello World!"";
}
}
";
Can this be done? Any advice, thanks!
You can try to use masterpage's codebehind, to hadndle events, and dynamically create only content-pages.
Why create a code-behind at all when you can just add that code in the aspx-file? Much simpler and you still have all your page_load events and such

Find A Control (Inside Master Page) From Content Page, Error = NullReferenceException

Please See The Simple Example Below For Understanding My situation.
(Attention To Comments Inside Codes)
Master Page (ASPX) :
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="NiceFileExplorer.Site1" %>
<!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 runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<span runat="server" id="SummaryContainer">
<asp:Label ID="lblDownload_Count_By_UserID_Today_Title" runat="server" Text="Count :"
ToolTip="Your Download Count-Today" CssClass="lblTitleInStatistics_Master"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID_Today" runat="server" Text="<%# Download_Count_By_UserID_Today() %>"
CssClass="lblCountInStatistics_Master" ToolTip="Your Download Count-Today"></asp:Label>
<span style="color: white;"> | </span>
<asp:Label ID="lblDownload_Size_By_UserID_Today_Title" runat="server" Text="Size :"
ToolTip="Your Download Size-Today" CssClass="lblTitleInStatistics_Master"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today" runat="server" Text="<%# Download_Size_By_UserID_Today() %>"
CssClass="lblCountInStatistics_Master" ToolTip="Your Download Size-Today"></asp:Label>
</span>
</div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" ViewStateMode="Inherit" ClientIDMode="Static">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
as you see i set ClientIDMode="Static".
Master Page (CodeBehind) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NiceFileExplorer
{
public partial class Site1 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
SummaryContainer.DataBind();
}
protected string Download_Count_By_UserID_Today()
{
//Read New Count From DataBase
//return Count;
return "Test";
}
protected string Download_Size_By_UserID_Today()
{
//Read New Size From DataBase
//return Size;
return "Test";
}
}
}
Content Page (ASPX) :
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="NiceFileExplorer.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
Conntent Page
</asp:Content>
Content Page (CodeBehind) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NiceFileExplorer
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyMethod();
}
private void MyMethod()
{
//Add New Downloaded File Info To DataBase(); -> For Getting Count And Size Of Them Per Day
//Here I Wand To Access Master Page Controls And Update Count And Size Lables
//So, I Tried Codes Below Without Any Results -> How Can I Fix This ?
var SummaryContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.Master.FindControl("SummaryContainer");
SummaryContainer.DataBind();
SummaryContainer.InnerHtml = "<h2>Hello World</h2>";
//After Update Those Lables Failed, I test the codes Below With Null Execption Error -> How Can I Fix This ?
var lblDownload_Count_By_UserID_Today_Title = (Label)Page.Master.FindControl("lblDownload_Count_By_UserID_Today_Title");
lblDownload_Count_By_UserID_Today_Title.Text = "test";
DwonloadFile();
}
private void DwonloadFile()
{
//A Class (Method) That Shows Download Window To My Users, So Page_Load Of Master Will Never Fire...
//And This Is The Reason That I want to update count & size lables from content page
}
}
}
i want to DataBind SummaryContainer(a span) from content page's code-behind.
so i tried the codes below :
var SummaryContainer = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.Master.FindControl("SummaryContainer");
SummaryContainer.DataBind():
but i can not see new results.
After That Fail I tried to find a label's text(that label is inside Master) from content page code behind for test like below : var
lblDownload_Count_By_UserID_Today_Title = (Label)Page.Master.FindControl("lblDownload_Count_By_UserID_Today_Title");
lblDownload_Count_By_UserID_Today_Title.Text = "test";
but i have System.NullReferenceException ERROR :
Object reference not set to an instance of an object.
how can i fix that error and force that span to show me new results?
thanks in advance
In a project I used an interface on the masterpage:
((IMasterPage)Page.Master).MyProperty = "test";
But in your case, personally instead of putting all that on the master page, I'd put your SummaryContainer into a UserControl, and have another ContentPlaceHolder.
Then the Page_Load method will be able to access the properties, and on future pages you could have different summary info by filling that first PlaceHolder with a different UserControl.
Also debugging stupid errors, is the Null exception being thrown at .Master.FindControl or at lbl.Text?
I'm unable to debug it for myself right now, but would it be due to the page life cycle, namely that Content Page Load comes before Master Page Load?

submit button click

I have GUI for data acceptance.
I need to pass all the parameters of the form on click of a submit button to a function declared in C#.
Please help.
Using .Net us have too types of submit tags, one starting with <asp: and the other starting with <input. the <input html tag can call javascript and if you add the runat="server" attribute, you will enable it to also have C# code behind the button.
First of all, you will need to create an aspx page (say submission.aspx) that will receive the POST submission of your form. In that page, you can include your .cs file that contains the method/function you want to pass the data to.
Next, you want to submit you submit your data to submission.aspx. To do that, you will need to have a form which will submit its data to submission.aspx.
<form action='submission.aspx' method='POST' id='data-submission'>
<!-- stuff here -->
</form>
If you want to perform ajax submission, you can use jquery and use this code:
$('#data-submission').submit(function(evt){
var $form = $(this);
var url = $form.attr('action');
$.post(url, $form.serialize(), function(){alert('submission complete!);});
});
I wonder if all that helped you.
PS: I haven't used .NET for web programming in a long time now.. but what I've written here in this answer hold universally true for any web programming language/framework.
If your using asp.net you just need to double click the button(if it is an asp button) and it should make a click event.
In the click event you could get your other controls like
default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
// you can declare it as a field variable so the entire code behind can use it
private Passengerdetails myClass;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// create an instance of the class.
myClass = new Passengerdetails ();
// stick textbox1 contents in the property called test.
myClass.PassengerName = TextBox1.Text;
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
int sum = Add(a, b);
// do something with it like return it to a lbl.
Label1.Text = sum.ToString();
}
private int Add(int a, int b)
{
return a + b;
}
}
Edit. You just make a class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for passengerdetails
/// </summary>
public class Passengerdetails
{
public Passengerdetails ()
{
public string PassengerName{ get; set; }
}
}

Categories