Passing parameters beetween .aspx and .aspx.cs - c#

I am using Visual Studio 2015 Ultimate. I have put a raw HTML web form in my Test.aspx file and want to pass the parameters of form-fields (like : Username, password, mobile no. etc.) from Test.aspx to Test.aspx.cs file. Although, I have written the code for passing the values in the button click function, I can't get the data. I have written "string u = Request.QueryString["username"];" for username field (without quotes) and so on and another line to print the value in that form itself, that is "Response.Write(u);" (without quotes). Here, I can't see the printed values in my form. How can I solve this issue?
Register.aspx file-
<!-- Start Register Section -->
<div id="login-page">
<div class="layer-stretch">
<div class="layer-wrapper">
<div class="layer-container">
<form class="form-container" action="Register.aspx" method="post" enctype="multipart/form-data" runat="server">
<input type="hidden" name="_token" value="15276e55e6cdfa6911f440f75f64501dc97cc6f4a19102dddb4c47f0c4dd1523ad639943996afef209d6a358056f3b3389a9bcb175b7413ef3547589673a2b7d">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-user-o"></i>
<input class="mdl-textfield__input" type="text" name="fullname" pattern="[A-Z,a-z, ]*" id="register-first-name" runat="server">
<label class="mdl-textfield__label" for="register-first-name">الاسم الكامل<em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال اسم كامل صالح!</span>
</div>
<!--<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-user-o"></i>
<input class="mdl-textfield__input" type="text" name="lastname" pattern="[A-Z,a-z, ]*" id="register-last-name">
<label class="mdl-textfield__label" for="register-last-name">الكنية <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال الاسم الصحيح!</span>
</div>-->
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-envelope-o"></i>
<input class="mdl-textfield__input" type="text" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" id="register-email" runat="server">
<label class="mdl-textfield__label" for="register-email">البريد الإلكتروني <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال بريد إلكتروني صحيح!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-phone"></i>
<input class="mdl-textfield__input" type="text" name="mobile" pattern="[0-9]*" id="register-mobile" runat="server">
<label class="mdl-textfield__label" for="register-mobile">رقم الهاتف المحمول <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال رقم الجوال صحيح!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-key"></i>
<input class="mdl-textfield__input" type="password" name="password" id="register-password" runat="server">
<label class="mdl-textfield__label" for="register-password">كلمه السر <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال كلمة المرور صالحة (الحد الأدنى 6 حرف)!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-key"></i>
<input class="mdl-textfield__input" type="password" name="confirmpassword" id="register-confirm-password" runat="server">
<label class="mdl-textfield__label" for="register-confirm-password">تأكيد كلمة المرور <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال تأكيد كلمة المرور (الحد الأدنى 6 حرف)!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon form-bot-check">
<i class="fa fa-question"></i>
<input class="mdl-textfield__input" type="number" name="bot-check" id="register-bot" runat="server">
<label class="mdl-textfield__label" for="register-bot">ما هو 10 زائد 3 =<em>* </em></label>
<span class="mdl-textfield__error">الرجاء إدخال القيمة الصحيحة!</span>
</div>
<!--<div class="login-condition">بالنقر على "إنشاء حساب" فإنك توافق على موقعنا<br />شروط & الظروف</div>-->
<div class="form-submit">
<!-- <button class="mdl-button mdl-js-button mdl-js-ripple-effect button button-primary" name="register" onclick="Submit_Click">إصنع حساب</button>-->
<asp:Button ID="Button1" runat="server" OnClick="Submit_Click" Text="Submit" class="mdl-button mdl-js-button mdl-js-ripple-effect button button-primary" />
<asp:Button ID="Button2" runat="server" Text="Register" class="mdl-button mdl-js-button mdl-js-ripple-effect button button-primary" OnClick="Button2_Click" />
</div>
<div class="login-link">
<span class="paragraph-small">هل لديك حساب؟</span>
تسجيل الدخول
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Register Section -->
Register.aspx.cs file-
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MDC_web {
public partial class Register: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
protected void Submit_Click(object sender, EventArgs e) {
System.Diagnostics.Debug.WriteLine("Register button has been clicked!!");
string fn = String.Format("{0}", Request.Form["fullname"]);
Response.Write("<script language='JavaScript'> alert('jhkjhjk');</script>");
Response.Write(fn);
string em = Request.QueryString["email"];
Response.Write(em);
string mob = Request.QueryString["mobile"];
Response.Write(mob);
string p = Request.QueryString["password"];
string cp = Request.QueryString["confirmpassword"];
/*if (p.Equals(cp))
{
string c = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Register (R_Name, Email, Mobile, R_Pass) values ('" + fn + "','" + em + "'," + mob + ",'" + p + "')", con);
int r = cmd.ExecuteNonQuery();
if (r == 1)
{
Response.Write("<script language='JavaScript'> alert('Registration is successfull!!');</script>");
}
}*/
}
/*protected void Button2_Click(object sender, EventArgs e)
{
Response.Write("<script language='JavaScript'> alert('jhkjhjk');</script>");
//Response.Write(fn);
}*/
}
}

for use form-fields values in .cs you have to do targetting like this
string Username = txtUsername.Value.Trim(); (txtUsername is the name of field in aspx)
string Password = txtPassword.Value.Trim();
string Mobile = txtMobile.Value.Trim();
the query string is used for passing value trough aspx pages not for aspx to cs

You can access asp id from the .aspx in your .aspx.cs.
just give them a unique ID and runat like so:
.aspx
<asp:TextBox runat="server" ID="txtUsername"></asp:TextBox>
.aspx.cs
var username = txtUsername.Text;
this is for receiving the text of the textbox. If you want to set the text then simply change it to txtusername.Text = "test test". You can to this also with asp:labels, asp:button etc.
Check this post for more informations
If you want to do that on a button click just make use of the postback which happens after the click.
.aspx
<asp:TextBox runat="server" ID="txtUsername"></asp:TextBox>
<asp:Button runat="server" ID="btnSumbit" Text="submit"></asp:Button>
.aspx.cs
protected void btnSumbit_Click(object sender, EventArgs e){
var username = txtUsername.Text;
//do username stuff in here
}
if you need a Tutorial for a login form with websforms check one of these:
https://msdn.microsoft.com/en-us/library/ff184050.aspx
https://www.youtube.com/watch?v=QoPABrUknsE

Do not transmit a password, in plain text, via a query string. Set up a https connection for your production site - you can do it free with Let's Encrypt. You say you added a "raw HTML form" - add plain HTML elements but do not add an extra form element because ASPNET can only handle a single form with a runat="server" attribute.
Then, to use plain HTML, just add runat="server" so that you can grab the data on the server side:
Test.aspx:
User Name: <input type="text" name="userName" runat="server">
Test.aspx.cs
string userName = userName.Value.Trim();
UPDATE:
If you're using a master page, why have you got a form tag in the aspx? The master page usually contains the form tag so it looks like you're copying and pasting code from somewhere else. Remove the form tag from your aspx.
Don't pass sensitive information in the URL via a query string. Use a single form tag in your master page, then in your code-behind:
string fName = register-first-name.Value;
You're using ASPNET so there is no point in the pattern attribute. Simply add a Regular Expression validator control.

Related

Call Server Side Function On HTML Button Click

I have one button when i click on it... first my DIV gets execute/loaded which is working fine for me.
Now parallel i want to send an email to my account how i can call my server side function. Means when Admin click on "Mail Account Detail" i want to pop up DIV as well as Call my Server Side function names "SendAnEmail".
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#patPortalCredDiv">Mail Account Detail</button>
Here is my Div Code.
<div id="patPortalCredDiv" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" style="color: black;">Mail Credential</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<h4 for="UserName">Note:-
<asp:Label type="text" runat="server" Text="" ID="txtMail"></asp:Label>
</h4>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Here is my server side function which i want to call also.
protected void SendAndEmail(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Server Side Code Also executed.');", true);
}
Problem in this case were data-toggle and data-target attributtes preventing page to post back.
In your aspx page replace your button for this:
<asp:Button Text="Mail Account Detail" OnClick="SendAndEmail"
CssClass="btn btn-primary" type="button" runat="server" />
In your C# code behind
protected void SendAndEmail(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert",
"$('#patPortalCredDiv').modal('show');", true);
}
This will open bootstrap modal using jQuery
This is what I have done.
I am using HTML and Java for the back-end to send the mail.
<body>
<h3> Please Enter your Email Address </h3>
<form action="Sendmail" method="post">
<input type="text" class="form-control" placeholder="staff_email" email="staff_email">
<input type="submit" value="Submit">
</form>
</body>
On the back end side, I am using Gmail service.
public class EmailUtility{
public static void sendEmail(String host, String port,
final String senderEmail, String senderName, final String password,
String recipientEmail, String subject, String message) throws AddressException,
MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, password);
}
};
Session session = Session.getInstance(properties, auth);
//creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderEmail));
InternetAddress[] toAddresses = { new InternetAddress(recipientEmail) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
//sends the e-mail
Transport.send(msg);
}
}
I am using Tomcat Server. Please add the following lines in the web.xml of Tomcat Server.
<context-param>
<param-name>email</param-name>
<param-value>abc#gmail.com</param-value>
</context-param>
<context-param>
<param-name>name</param-name>
<param-value><Your Name></param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value> Your Password Comes Here </param-value>
</context-param>

Getting data from HTML to C#

I am using this HTML code (bootstrap) to allow users to enter tags
<div class="bootstrap-tagsinput"> <span class="tag label label-info">test tag<span data-role="remove"></span></span> <span class="tag label label-info">testing <span data-role="remove"></span></span> <span class="tag label label-info">issue <span data-role="remove"></span></span> <input size="1" type="text"> </div>
So the output
My question is, I cannot figure out how do I read this text in C# (asp.net Web forms) because it's not ASP:TextBox
Is this possible to read these tags in C#?
Thank you
So by looking at the documentation here: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ you should be applying data-role="tagsinput" to the input element. This means you should be able to do something like:
Important Update : I threw this together before my morning coffee had kicked in. Note that asp:button has become asp:TextBox
<div class="bootstrap-tagsinput">
<span class="tag label label-info">test tag<span data-role="remove"></span></span>
<span class="tag label label-info">testing <span data-role="remove"></span></span>
<span class="tag label label-info">issue <span data-role="remove"></span></span>
<asp:TextBox ClientIDMode="Static" ID="tags" runat="server" data-role="tagsinput" />
</div>
You can then access the values from tags as a comma delimited string.
Alteratively you could try
<div class="bootstrap-tagsinput">
<span class="tag label label-info">test tag<span data-role="remove"></span></span>
<span class="tag label label-info">testing <span data-role="remove"></span></span>
<span class="tag label label-info">issue <span data-role="remove"></span></span>
<input id="tags" runat="server" size="1" type="text" data-role="tagsinput" />
</div>
This will make the text input available as a comma delimited string server side, again using tags.
Finally the least webformy option, just give the input a name attribute
<div class="bootstrap-tagsinput">
<span class="tag label label-info">test tag<span data-role="remove"></span></span>
<span class="tag label label-info">testing <span data-role="remove"></span></span>
<span class="tag label label-info">issue <span data-role="remove"></span></span>
<input name="tags" size="1" type="text" data-role="tagsinput" />
</div>
You can then access it serverside with Request.Form["tags"], with, you guessed it, the tags as a comma delimited string.
Try this approach, using JQuery:
Client side:
<div class="bootstrap-tagsinput">
<span class="tag label label-info">test tag<span data-role="remove"></span></span> <span class="tag label label-info">testing <span data-role="remove"></span></span> <span class="tag label label-info">issue <span data-role="remove"></span></span>
<input size="1" type="text">
</div>
<input type="submit" id="sendTagsToServer" text="Send Tags To Server!"/>
<!--Both buttons are invisible, to postback and send parameters-->
<asp:Button ClientIDMode="Static" ID="postbackButton" runat="server"
Style="display:none;" />
<asp:HiddenField ClientIDMode="Static" ID="tagsString" runat="server" />
<script>
$(document).ready(function(){
$("#sendTagsToServer").on("click",function(){
//get values from tags
var tags= $(".tag");
//save values in hidden
var tagText = "";
tags.each(function(index){
tagtext = tagText + "&" + $(this).text();
});
$("#tagsString").val(tagText);
//postback to server
$("#postbackButton").click();
});
});
</script>
Server side:
protected void btnPB_Click(object sender, EventArgs e)
{
//read tags, server side
string[] param = tagsString.Value.Split("&");
}
The trick here is use two inputs, both hidden, one to postback and one to send parametters and of course, you can use Javascript instead of JQuery.

How to "send" form data to a C# code, then have C# "send" data back?

This is the HTML form I have, I want to send the user's selection to an aspx.cs file that will process their selection and output something onto the lower textbox.
<!-- Form -->
<form action="lGen.aspx" method="post" id="lForm" runat="server">
<div class="row">
<div class="input-field col s6">
<select id="list" form="lForm">
<option value="" disabled="disabled" selected="selected">Select</option>
<option value="1" class="validate" >Option 1</option>
</select>
</div>
<div class="input-field col s6">
<input placeholder="Instert Text" id="insText" type="text" class="validate" runat="server" />
<label for="system_id"></label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
Checkbox
<p class="black-text">
<input type="checkbox" class="filled-in" id="check1" />
<label for="check1"><span class="black-text">Check 1</span></label>
</p>
<p class="black-text">
<input type="checkbox" class="filled-in" id="check2" />
<label for="check2"><span class="black-text">Check 2</span></label>
</p>
</div>
<div class="input-field col s6">
Radio
<p>
<input class="with-gap" name="licenseType" type="radio" id="radio1" />
<label for="radio1"><span class="black-text">Permanent</span></label>
</p>
</div>
</div>
<div class="row">
<br />
<button class="btn waves-effect waves-light black" onclick="generate_onclick()">
Generate
</button>
</div>
</form>
<!-- TEXT AREA-->
<div class="row">
<div class="input-field col s12">
<textarea id="genText" class="materialize-textarea"></textarea>
<label for="genText"><span class="black-text">Generated</span></label>
</div>
</div>
The aspx.cs I have is this:
namespace lGenerator
{
public partial class WebForm1 : System.Web.UI.Page
{
public string list{ get; set; }
public bool check1{ get; set; }
public bool check2{ get; set; }
public bool radio1{ get; set; }
public string genText { get; set; }
// Generate License on Click button
private void generate_onclick(object sender, EventArgs e)
{
genL();
}
// Creating actual license
private void genL()
{
string phrase = list;
licenseText = phrase;
}
}
}
Just for testing, I wanted to pass the value of whatever they selected on the list and then show it on the textbox below. I'm aware that in PHP, you can use things like $_POST to get values from post but how do I do it with HTML and C#?
Note that I had to change some of the values/IDs and I need to get it working with C# because I will be working with .dlls in the future.
make those controls as server side control by including the property Runat="server" and then you can access those control instance values anywhere in your code behind (I mean *.cs file).

Email Attachment No Longer Working As Custom Styled ASP:FileUpload Field

I have an asp.net application which allows a file upload and I had this working correctly but now I have custom styled my file upload field it's no longer working and I can't figure out how to get it working again with my new styled field.
OLD HTML
<div class="form-group">
<asp:Label ID="Label3" class="col-md-3 control-label" runat="server" Text="Upload"></asp:Label>
<div class="col-md-3">
<asp:FileUpload ID="fuAttachment" runat="server" class="fileupload"></asp:FileUpload>
</div>
</div>
OLD Code Behind
var file = fuAttachment.PostedFile;
if (file != null && fuAttachment.PostedFile.FileName != "")
{
var content = new byte[file.ContentLength];
file.InputStream.Read(content, 0, content.Length);
Session["FileContent"] = content;
Session["FileContentType"] = file.ContentType;
Session["File"] = fuAttachment.FileName;
Session["AttachmentProvided"] = "Yes";
}
NEW HTML
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput" style="background-color: #ededed">
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new">
<span class="glyphicon glyphicon-folder-open" title="Click to select a file."></span>
</span>
<span class="fileinput-exists">
<span class="glyphicon glyphicon-folder-open" title="Click to change the selected file."></span>
</span>
<input type="file" name="...">
</span>
<a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">
<span class="glyphicon glyphicon-remove" title="Remove selected file."></span>
</a>
</div>
I need to store in my session as this populates another page so I need similar code behind as I had
Edit file input to :
<input type="file" id="fuAttachment" runat="server" />
Now you use fuAttachment from codebehind for access uploaded file.
Note: If runat="server" attribute is missing you don't able to control this input from codebehind.

C#/aspx.net process Post Values form

I'm quite new on aspx development, and I'm struggling a lot with the connection of aspx code and aspx.cs, precisely I've following problem :
DisplayChars.aspx :
<form id="form1" runat="server">
<div>
<div>Champion name: </div> <div><input id="Champ_name" type="text" /></div>
<div>Champion Icon URL: </div> <div><input id="Champ_icon" type="text" /></div>
<div>Champion Subtext: </div> <div><input id="Champ_subtext" type="text" /></div>
<div> Free to play :</div><div><input id="Champ_freetoplay" type="checkbox" />
</div>
<div>Positions:</div>
<div>
<input id="Top" type="checkbox" /> Top
<input id="Mid" type="checkbox" /> Mid
<input id="Jungle" type="checkbox" /> Jungle
<input id="Carry" type="checkbox" /> Carry
<input id="Support" type="checkbox" /> Support
</div>
</div>
<input id="Champ_Submit" type="submit" value="submit" />
DisplayChars.aspx.cs
if (IsPostBack)
{
//NameValueCollection nvc = Request.Form.GetValues
//Champion t1 = new Champion(Request.Form.Get("Champ_Name"), Int32.Parse(Request.Form.Get("Champ_freetoplay")), Request.Form.Get("Champ_subtext"), Request.Form.Get("Champ_description"), "10110");
//t1.persistChampion();
string temp = Request["Champ_name"];
So I'm struggling with getting the Form-values some how.
I've tried Request.Form.GetValues,Request.Form.Get even Request["Form_id_Name"].
The Question is, if this approach is even right, as I've experience in Object-oriented programming, but not in this combination of HTML aspx pseudo server code, and a cs-file behind it.
If you add runat="server" to you HTML tags and you can access their properties from the code-behind:
// DisplayChars.aspx:
<input id="Champ_name" type="text" runat="server" />
...
// DisplayChars.aspx.cs:
string champName = Champ_name.Value;
While you can do
Request.Form["Champ_name"]
It is not the asp.net way. You have to make the element a server control by adding runat="server" so you can reference it from code behind.
<asp:Button ID="Champ_name" runat="server" OnClick="button_Click" Text="Hello World" />
Then in your codebehind can add a method to fire when that button is clicked:
protected void button_Click(object sender, EventArgs e)
{
// logic processing here
}
If you needed to find out what the text of the button is:
string text = Champ_name.Text;
Basically, ASP.NET doesn't rely on Request.Form normally. You set the controls to runat="server" so you can address them directly from code-behind on postback.

Categories