Web-Form not accepting responses(Asp.net) - html

Recently i am working on a web-form written in asp.net framework. I have kept in mind to include !IsPostBack() but yet my form is not accepting the responses and updating the database accordingly.
The body of the .aspx code which basically contains 4 RadioButtonList and one textbox. Here is the code for one of the RadioButtonList and the textBox, the submit button and and a link button:
<li class="form-line jf-required" data-type="control_scale" id="id_24">
<label class="form-label form-label-top form-label-auto" id="label_24" for="input_24">
Do you feel the training provided value for money/time?
<span class="form-required">*
</span>
</label>
<asp:RadioButtonList ID="RadioButtonList4" runat="server" AutoPostBack="True" CellPadding="10" CellSpacing="10" RepeatDirection="Horizontal" Font-Names="Comic Sans MS" Font-Size="Large" Height="50px">
<asp:ListItem Value="1" class="radiobuttonlist1">Worse</asp:ListItem>
<asp:ListItem Value="2" class="radiobuttonlist2">Boring</asp:ListItem>
<asp:ListItem Value="3" class="radiobuttonlist3">Satisfactory</asp:ListItem>
<asp:ListItem Value="4" class="radiobuttonlist4">good</asp:ListItem>
<asp:ListItem Value="5" class="radiobuttonlist5">Fantastic</asp:ListItem>
</asp:RadioButtonList>
</li>
<li id="cid_27" class="form-input-wide" data-type="control_head">
<div class="form-header-group header-default">
<div class="header-text httal htvam">
<h2 id="header_27" class="form-header" data-component="header">Final Thoughts?
</h2>
</div>
</div>
</li>
<li class="form-line" data-type="control_textarea" id="id_45">
<label class="form-label form-label-top form-label-auto" id="label_45" for="input_45">REMARKS / SUGGESTIONS</label>
<div id="cid_45" class="form-input-wide" data-layout="full">
<asp:TextBox ID="TextBox1" runat="server" style="width: 40px; height: 6px"></asp:TextBox>
</div>
</li>
<li id="cid_28" class="form-input-wide" data-type="control_head">
<div align="center">
<asp:Button ID="Button1" runat="server" Text="Submit" Text-align="center" CssClass="btn btn-primary" OnClick="Button1_Click" BackColor="#66FFCC" Height="40px" Width="80px" />
</div>
<div>
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="btn btn-link" OnClick="LinkButton1_Click">Go back to Home Page</asp:LinkButton>
<br />
<br />
</div>
Here is the .aspx.cs of Page_Load:
public MySqlConnection mycon;
public MySqlCommand MyCm, cmd1;
public MySqlDataAdapter myad;
string userId;
protected void Page_Load(object sender, EventArgs e)
{
userId= Session["newFeedback"].ToString();
try
{
mycon = new MySqlConnection("server=localhost;database=feedbackform;user id=abcd;password=abcdabcd;");
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Here is the .aspx.cs code for Button_Click:
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Check_feedback_Exists())
{
Response.Write("<script>alert('You have already filled feedback form')</script>");
}
else
{
try
{
if (mycon.State == ConnectionState.Closed)
{
mycon.Open();
}
MySqlCommand cmd = new MySqlCommand("insert into feedback (Reference_Number, Feed1,Feed2,Feed3,Feed4,Remarks_Suggestion)values(userId, RadioButtonList1.SelectedItem.Text,RadioButtonList2.SelectedItem.Text,RadioButtonList3.SelectedItem.Text,RadioButtonList4.SelectedItem.Text,Textbox1.Text);", mycon);
cmd.ExecuteNonQuery();
mycon.Close();
Response.Write("<script> alert ('hello success'); </Script>");
}
catch (Exception ex)
{
Response.Write("<script> alert ('" + ex.Message + "'); </Script>");
}
}
}
}
Here is the code for the Check_feedback_exists:
bool Check_feedback_Exists()
{
try
{
if (mycon.State == ConnectionState.Closed) //checking that the connection between database and our project is open or not if not then open it
{
mycon.Open();
}
MySqlCommand cmd = new MySqlCommand("select * from feedback where Reference_Number = '" + userId + "' ; ", mycon);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Response.Write("<script> alert ('" + ex.Message + "'); </script>");
return false;
}
}
The check_feedback_exists function is working well since if i submit for an already existing feedback, it gives the alert message: 'You have already filled feedback form' as coded in the Button1_click function. But if i enter a new feedback for a new user and click on submit, it doesn't enter the database, neither shows the success alert. Here is the database description in which I am inserting these values:

Makes no sense to check !IsPostBack in a button click. Such a button click will ALWAYS be a post-back. So, that's confusing.
And same goes for your sql insert. Your trying to insert the "text" of the control.
eg this:
string strSQL =
"insert into feedback (Reference_Number, Feed1, Feed2, Feed3, Feed4, Remarks_Suggestion) " +
"VALUES (#userId, #RB1,#RB2,#RB3,#RB4,#TBOX1"
SqlCommand cmd = new SqlCommand(strSQL, conn);
cmd.Parameters.Add("#usewrId", SqlDbType.Int).Value = userid;
cmd.Parameters.Add("#RB1", SqlDbType.NVarChar).Value = RadioButtonList1.SelectedItem.Text;
cmd.Parameters.Add("#RB2", SqlDbType.NVarChar).Value = RadioButtonList2.SelectedItem.Text;
etc. etc. etc.
Now, I used the sql provider, - it looks like your using MySQL. But, the sytnax should be simular to above. So, for your insert, you can't use a string of
string strSQL = "textBox1.Text, TextBox2.Text"
Since that string will have the above textbox names as string.
You would need
string strSQL = "VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "')"
But, the above is dangerous - due to sql injection. So use the above parameters approach.
And remove the !IsPostBack from your button stubb - not required, and a button click is ALWAYS a post-back anyway.

Related

Unable to use html controls from code behind

I am using html tags and I have written some code on code behind but it is not picking the values given to id. Infact it says the 'FileUpload1' does not exist in the current context. I do not want to use asp controls at all. I have heard adding runat = "server" does the thing but still cannot find the id's. What am I doing wrong?
<div id="mainContent">
<div class="column" id="colFull">
<div class="contentSection">
<div id="progress" style="display: none">
<img alt="Loading .." src="../../../Images/ajax.gif" />
</div>
<table width="100%">
<tr>
<td class="label" style="width:15%">
Upload File
</td>
<td class="description" >
<input type="file" id="FileUpload1" runat="server"
class="largeTextField" onclick="Upload" multiple="multiple"
style="width:260px;"/>
<input type="button" id="btnUpload"
runat="server" value="Upload" />
</td>
</tr>
</table>
mycodebehind:
public partial class PgPracFileUploader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
It says FileUpload1 does not exist in the current context.
Try to change:
<input type="file" id="FieUpload1" runat="server" class="largeTextField" onclick="Upload" multiple="multiple" style="width:260px;"/>
to
Id Must be same as you are using in the .cs page
\/\/\/\/
<input type="file" ID="FileUpload1" runat="server" class="largeTextField" onclick="Upload" multiple="multiple" style="width:260px;"/>
As stated here your id attribute is case sensitive so you are using id then the server will just serve it up as it is in your page, but if you used ID then the server will be serve that control as a asp.net control.

Post form with JSP + AJAX + MYSQL, without refresh page?

I have problem with send form without refresh page in JSP using AJAX. How can I create AJAX to send this form, from index.jsp to send.jsp without refresh page ? Thanks for all your answers.
This is form code and it s work, without AJAX. (index.jsp)
<form id="dom-realitka-notifikacia" action="send.jsp" method="post" >
<div class="stred">
<b class="cierna">E-mail:</b>
<input type="text" class="form-control form-rovno" id="email" name="email" placeholder="Sem napíšte e-mail">
<input type="hidden" value="domrealitka" id="tabulka" name="tabulka">
<input type="hidden" value="<%= rs.getInt("id") %>" id="id_realitka" name="id_realitka">
<button type="submit" class="btn btn-success">Odoslať</button>
</div>
</form>
And this is (send.jsp), work without AJAX and insert into MYSQL.
page contentType="text/html" pageEncoding="UTF-8"
page import="javax.mail.*"
page import="javax.mail.internet.*"
page import="javax.sql.*"
page import="javax.naming.Context"
page import="javax.naming.InitialContext"
page import="java.sql.*"
request.setCharacterEncoding("UTF-8");
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String email = request.getParameter("email");
int id_realitka = Integer.valueOf(request.getParameter("id_realitka"));
String tabulka = request.getParameter("tabulka");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("nacitala sa driver");
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/janko");
con = ds.getConnection();
System.out.println("nacitala sa databaza");
String sql = "INSERT INTO janko.notifikacia (email, id_realitka, tabulka) VALUES ( ?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, email);
ps.setInt(2, id_realitka);
ps.setString(3, tabulka);
ps.executeUpdate();
con.close();
}
catch(ClassNotFoundException e1) //ClassNotFoundException dame Class.forName a klikneme ctrl+space a e1 dopiseme hocico
{
System.out.println(e1.getMessage()); //vypis spravy e1 do konzoly
}
catch(SQLException e2) //SQLException mame z DriverManager.getConnection po kliknuti ctrl+space a e2 dopiseme hocico
{
System.out.println(e2.getMessage()); //vypis spravy e2 do konzoly
}
finally{
con = null;
rs = null;
ps = null;
}
The form can be dynamically submitted easily using jQuery. Just include jQuery in your file and paste the following code in your HTML file.
<script>
$.ajax({url: "send.jsp",
data: $('#dom-realitka-notifikacia').serialize(),
success: function(result){
//do something like showing success message
}});
</script>
This code will serialize your form data and send it to the concerned servlet. The servlet code remains the same.

How to Create Hyperlink to Uploaded files to open the file

Hi Below is the code for Uploading Multiple files I cant display all the file names at a time it shows only one file name and how to create hyperlink to Uploaded documents to view the files.
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
If FileUpload1.HasFile Then
Try
FileUpload1.SaveAs("Destinationpath\testing\\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.FileName & "<br>"
ListBox1.Items.Add(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName))
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
'Files.RemoveAt(ListBox1.SelectedIndex)
ListBox1.Items.Remove(ListBox1.SelectedItem.Text)
Label1.Text = "File removed"
End Sub
and below is the aspx code
<div>
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true"/><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Upload Document" /><br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label></div>
<asp:listbox ID="ListBox1" runat="server" Width="175px"></asp:listbox>
<asp:Button ID="Button2" runat="server" Text="Remove" Width="98px" OnClick="Button2_Click" />
can anyone help me to do this. Thanks..
Use ListBox for this. It will be something like:
protected void UploadButton_Click(object sender, EventArgs e){
foreach (HttpPostedFile fl in fu.PostedFiles)
{
fl.SaveAs(DestinationPath + fl.FileName);
ListItem li = new ListItem();
li.Text = fl.FileName;
ListBox1.Items.Add(li);
}
}
In your design page:
<asp:Panel ID="pnlFiles" runat="server" />
Your code behind:
Protected Sub Button1_Click(ByVal sender As Object, _ByVal e As System.EventArgs)
For Each fl as HttpPostedFile in fu.PostedFiles
Dim fileLink as String = DestinationPath + fl.FileName
fl.SaveAs(fileLink)
Dim hpr as New HyperLink
hpr.Text = "Download file"
hpr.NavigateUrl = fileLink
pnlFiles.Controls.Add(hpr)
Next
End Sub

Setting the Control in RadGrid to Visible-False

I need help with getting the ID of the Control in RadGrid in order to set it Visable=False.
The last function is actually creating a pic based on the value that's coming from the DB. How can I set the HyperLink next to the Pic that I'm adding to Visible false?
I think that I need to send that function RenderLinked the hyperlink control but I don't know how and I hope that some one can show me the way.
<telerik:RadGrid
ID="rgPhoneBook"
runat="server"
AutoGenerateColumns="False"
AllowPaging="True"
AllowSorting="True"
PageSize="50"
CellSpacing="0" GridLines="None"
OnItemCommand="rgPhoneBook_ItemCommand"
OnPageIndexChanged="rgPhoneBook_OnPageIndexChanged"
OnSortCommand="rgPhoneBook_OnSortCommand"
OnItemCreated="rgPhoneBook_OnItemCreated"
EnableHeaderContextFilterMenu="True"
Width="933px"
Height="528px">
<ClientSettings>
<Selecting AllowRowSelect="True"></Selecting>
<Scrolling AllowScroll="true" UseStaticHeaders="True" SaveScrollPosition="true" FrozenColumnsCount="2" />
</ClientSettings>
<MasterTableView ShowHeadersWhenNoRecords="true" NoMasterRecordsText="No PhoneBook Records to display" Font-Size="11px" GridLines="None" AllowPaging="True" ItemStyle-Height="25px" CommandItemDisplay="Top" AllowAutomaticUpdates="False" TableLayout="Auto" DataKeyNames="LocationID,PersonID" ClientDataKeyNames="LocationID,PersonID">
<PagerStyle Mode="NumericPages"></PagerStyle>
<Columns>
<telerik:GridTemplateColumn HeaderText="Linked" HeaderStyle-Width="45px" >
<ItemTemplate>
<span id="spanHyperLink" style="visibility:visible" runat="server">
<asp:HyperLink ID="Link" runat="server" Text="Link">
</asp:HyperLink>
</span>
<%# RenderLinked(DataBinder.Eval(Container.DataItem, "Linked"))%>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Protected Function RenderLinked(ByVal inputVal As String) As String
Dim output As String = ""
Try
Dim svcs As New SystemServices
If Not inputVal Is Nothing And Not String.IsNullOrEmpty(inputVal) Then
If inputVal = True Then
output = "<img src='" + Globals.gRootRelativeSecureURL("\Images\Layout\Link.png") + "' width=""13"" height=""13"" border=""0"" align=""absmiddle"">"
Else
'Dim item As GridDataItem = DirectCast(e.Item, GridDataItem)
'Dim link As HyperLink = DirectCast(item("Link").Controls(0), HyperLink)
'LinkButton.DisabledCssClass = True
Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "StartupScript", "Sys.Application.add_load(function() { DisableHyperLinkCSS(); });", True)
'output = "<a herf='#' onclick='showPersonLinkModal() ;'>Link</a>"
End If
End If
Catch ex As Exception
Globals.SendEmailError(ex, m_User.SessionID, System.Reflection.MethodBase.GetCurrentMethod.Name.ToString(), Request.RawUrl.ToString(), m_User.UserID)
End Try
Return output
End Function
If you want to set some control's attribute visible=false in code behind when rows are bound to data 1 by 1 you may use RowDataBound event and write following code in it's handler
Control_Type Control_ID = (Control_Type) e.Row.FindControl("Control_ID");
Control_ID.Visible = false;
And if you want to set it in javascript,
rgPhoneBook.Rows[Record_Index].Cells[0].Visible = false;
Hope this helps you. The above code is in C#, please convert it to it's equivalent in VB.

Partial page updating using update panel

I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?
Set AutoPostBack= true for the first ddl
U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}