I am trying to get my cascading comboboxes to work, but am getting a [Method error 500]. Any ideas? I've searched online, the code should work....Thanks in advance for your help!
ADDSTORY.ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="addstory.aspx.cs" Inherits="addstory" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
...
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server" />
...
<td class="style3">
<asp:DropDownList ID="selectproject" runat="server" Width="225"></asp:DropDownList>
<asp:CascadingDropDown ID="ccd1" runat="server"
ServicePath="~/dropdown.asmx?company=<%=co_id %>" ServiceMethod="GetProjects"
TargetControlID="selectproject" Category="Project"
PromptText="Select Project" />
</td>
</tr>
<tr>
<td class="style3"></td>
<td width = "150" class="style3">Iteration:</td>
<td class="style3">
<asp:DropDownList ID="selectiteration" runat="server" Width="225"></asp:DropDownList>
<asp:CascadingDropDown ID="ccd2" runat="server"
ServicePath="~/dropdown.asmx?company=<%=co_id %>" ServiceMethod="GetIterations"
TargetControlID="selectiteration" Category="Iteration"
PromptText="Select Iteration" />
</td>
</tr>
DROPDOWN.ASMX:
using System.Web.Script.Services;
using AjaxControlToolkit;
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SqlClient;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService()]
public class dropdown : System.Web.Services.WebService
{
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
}
[WebMethod]
public CascadingDropDownNameValue[] GetProjects(string knownCategoryValues, string category)
{
string co_id = this.Context.Request.QueryString["company"].ToString();
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand comm = new SqlCommand("Select ProjectName, ProjectID FROM Project WHERE CompanyID = '" + co_id + "'", conn);
SqlDataReader dr = comm.ExecuteReader();
List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
while (dr.Read())
{
l.Add(new CascadingDropDownNameValue(dr["ProjectName"].ToString(), dr["ProjectID"].ToString()));
}
conn.Close();
return l.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetIterations(string knownCategoryValues, string category)
{
int ProjectID;
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
if (!kv.ContainsKey("Project") || !Int32.TryParse(kv["Project"], out ProjectID))
{
throw new ArgumentException("Couldn't find project.");
};
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlCommand comm = new SqlCommand("SELECT Select CONVERT(VARCHAR(10), StartDate, 103) + ' - ' + CONVERT(VARCHAR(10), EndDate, 103) AS Iteration, ProjectIterationID FROM Iterations WHERE ProjectID=#ProjectID", conn);
comm.Parameters.AddWithValue("#ProjectID", ProjectID);
SqlDataReader dr = comm.ExecuteReader();
List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
while (dr.Read())
{
l.Add(new CascadingDropDownNameValue(dr["Iteration"].ToString(), dr["ProjectIterationID"].ToString()));
}
conn.Close();
return l.ToArray();
}
}
I see you have already flagged your service as ScriptService, however you forgot to flag individual methods with the [ScriptMethod] attribute.
Also in the service path property of your cascading drop down controls I would take out the ~ and just use /dropdown.asmx
Related
I got a 'grid view' and three buttons in my web form. Now when I click 'button1' I want to show the respective result for query1 in 'grid view' and for 'button2' it should show the result of query2. Same for button3.
HTML of my web form :
<%# Page Title="" Language="C#" MasterPageFile="~/Master Page/Site1.Master" AutoEventWireup="true" CodeBehind="Dashboard.aspx.cs" Inherits="onlineshopping.Master_Page.WebForm1" %>
<asp:Content ID="Content1" runat="server" contentplaceholderid="BillingContent">
<div>
<table>
<tr>
<td>
<asp:Button ID="btn_dsbrdItems" runat="server" Text="Show Items" />
</td>
<td style="width:20px"></td>
<td>
<asp:Button ID="btn_dsbrdShowInvoices" runat="server" Text="Show Invoices" />
</td>
<td style="width:20px"></td>
<td>
<asp:Button ID="btn_dsbrShowUsers" runat="server" Text="Show Users" />
</td>
<td style="width:20px"></td>
</tr>
</table>
<table>
<tr>
<td>
<asp:GridView ID="gv_dashboard" runat="server" AutoGenerateColumns="false">
</asp:GridView>
</td>
</tr>
</table>
I know that I can bind a query result to 'grid view' and I have done that before. But I don't know what to do to achieve this. And I tried something. I knew its stupid & not gonna work. Still I just tried and didn't work as I expected. This is what I tried.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace onlineshopping.Master_Page
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings.Get("connectionstring").ToString());
string sql = "";
DataSet ds = new DataSet();
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void btn_dsbrdItems_Click(object sender, EventArgs e)
{
if(con.State==ConnectionState.Closed)
{ con.Open(); }
sql = "select * from item";
da = new SqlDataAdapter(sql, con);
da.Fill(ds);
gv_dashboard.DataSource = ds;
gv_dashboard.DataBind();
con.Close();
}
protected void btn_dsbrdShowInvoices_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{ con.Open(); }
sql = "select * from invoice";
da = new SqlDataAdapter(sql, con);
da.Fill(ds);
gv_dashboard.DataSource = ds;
gv_dashboard.DataBind();
con.Close();
}
protected void btn_dsbrShowUsers_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{ con.Open(); }
sql = "select * from tbl_users";
da = new SqlDataAdapter(sql, con);
da.Fill(ds);
gv_dashboard.DataSource = ds;
gv_dashboard.DataBind();
con.Close();
}
}
}
This is my web form
I am using 'master page' for side 'menu'. If this question is asked before please help me to find that link. I couldn't find.
Experts,
Drop-down list is picking data from database and saving against the same column upon opening the web page and save the data, where saving is happening in another instead of same name,
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="form">
<p>
<asp:Label ID="Label1" runat="server" Text="Place Name" AssociatedControlID="txtName"></asp:Label>
<asp:DropDownList ID="txtName" runat="server" >
</asp:DropDownList>
</p>
<p>
<asp:Label ID="Label2" runat="server" Text="Address" AssociatedControlID="txtAddress"></asp:Label>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
</p>
<p>
<asp:HiddenField ID="hdnLocation" runat="server" />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" />
</p>
<p id="message"></p>
</div>
</form>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { $("#message").html("Geolocation is not supported by this browser."); }
function showPosition(position) {
var latlondata = position.coords.latitude + "," + position.coords.longitude;
var latlon = "Latitude" + position.coords.latitude + "," + "Longitude" + position.coords.longitude;
$("#message").html(latlon);
$("[id*=hdnLocation]").val(position.coords.longitude + " " + position.coords.latitude);
}
function showError(error) {
if (error.code == 1) {
$("#message").html("User denied the request for Geolocation.");
}
else if (error.code == 2) {
$("#message").html("Location information is unavailable.");
}
else if (error.code == 3) {
$("#message").html("The request to get user location timed out.");
}
else {
$("#message").html("An unknown error occurred.");
}
}
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Data.Entity.Spatial;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT PlaceID, Name,Address FROM Placeinfo";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Name"].ToString();
txtName.Items.Add(item);
txtName.ClearSelection();
}
}
con.Close();
}
}
}
}
public List<PlaceInfo> GetMyPlaces()
{
return new SampleDBEntities().PlaceInfoes.ToList();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
PlaceInfo placeToEdit = Context.placeinfoes.Find(Convert.ToInt32(txtName.DataValueField));
using (var context = new SampleDBEntities())
{
PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.DataValueField));
placeToUpdate.Name = txtName.Text;
placeToUpdate.Address = txtAddress.Text;
placeToUpdate.Geolocation = DbGeography.FromText("POINT( " + hdnLocation.Value + ")");
context.Entry(placeToUpdate).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
}
}
databaseDATABASE DISPLAY
In order to update an item in a database, we first need to make sure we'll know which one we need to reference.
First, with the creation of your DropDownList, we'll want to hide the ID of the "PlaceInfo" we are displaying. This will create the need for a "SelectMethod", and a few other adjustments:
<asp:DropDownList ID="txtName" runat="server" ItemType="PlaceInfo" DataValueField="PlaceId" DataTextField="Name" SelectMethod="GetMyPlaces"></asp:DropDownList>
The DataTextField property is the one which will display in the actual DropDown, and the DataValueField is a hidden property which we will use to reference the ID so we can call that row later.
The SelectMethod (I have as: GetMyPlaces) is the method we use to populate the DropDownList. Please excuse the brevity, as you can do this a number of ways, but essentially you want to return a list of PlaceInfos:
public List<PlaceInfo> GetMyPlaces()
{
return new SampleDbEntities().PlaceInfoes.ToList();
}
Finally - in the btnSubmit_Click method, you want to grab the row we're going to edit by using the hidden Value field from the dropdown :
PlaceInfo placeToEdit = Context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value))
Assign it the new values, and tell entity framework this model is now modified:
using (var context = new SampleDBEntities())
{
PlaceInfo placeToUpdate = context.PlaceInfoes.Find(Convert.ToInt32(txtName.Value));
placeToUpdate.Name = txtName.Text;
placeToUpdate.Address = txtAddress.Text;
placeToUpdate.Geolocation = DbGeography.FromText("POINT( "+hdnLocation.Value+")");
context.Entry(placeToUpdate).State = EntityState.Modified;
context.SaveChanges();
}
Save the changes to your context and you should be good to go.
I know this is a fairly common error, however the circumstances for me in this case are a little different.
Sometimes, I will not get this error, other times I will, which is not ideal.
Usually I change the inherit name and change the public partial class to the same and it works fine, but after a while I will receive the following.
Error 1 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 31 13 Branch(3)
Error 2 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 32 13 Branch(3)
Error 3 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 33 13 Branch(3)
Error 4 The name 'add_modules' does not exist in the current context all-modules.aspx.cs 34 13 Branch(3)
Error 5 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 42 13 Branch(3)
Error 6 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 43 13 Branch(3)
Error 7 The name 'display_modules' does not exist in the current context all-modules.aspx.cs 44 13 Branch(3)
Below is my C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
public partial class all_modules: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
//Only allow admins, academic program managers and Senior University Managers to view page
helper.Authorised(1, 2, 3);
//get role_id of logged in user
int role_id;
role_id = Convert.ToInt32(Session["role_id"]);
//get id of logged in user
string user_id = Session["user_id"].ToString();
//if admin
if (role_id == 1 || role_id == 3) {
string query = "SELECT courses.course_name, staff_records.f_name, staff_records.l_name, modules.module_name, modules.module_tutor, modules.module_id FROM courses_vs_modules INNER JOIN modules ON courses_vs_modules.module_id = modules.module_id INNER JOIN staff_records ON modules.module_tutor = staff_records.user_id INNER JOIN courses ON courses_vs_modules.course_id = courses.course_id WHERE (courses.school IN (SELECT school_id FROM staff_records AS staff_records_1 WHERE (user_id = #user_id))) ORDER BY courses.course_name";
DataTable dt = GetData(query, user_id);
display_modules.DataSource = dt;
display_modules.DataBind();
display_modules.Visible = true;
add_modules.Visible = true;
}
//if senior uni manager
if (role_id == 2) {
string query = "SELECT courses.course_name, staff_records.f_name, staff_records.l_name, modules.module_name, modules.module_tutor, modules.module_id FROM courses_vs_modules INNER JOIN modules ON courses_vs_modules.module_id = modules.module_id INNER JOIN staff_records ON modules.module_tutor = staff_records.user_id INNER JOIN courses ON courses_vs_modules.course_id = courses.course_id ORDER BY courses.course_name";
DataTable dt = GetDataSen(query);
display_modules.DataSource = dt;
display_modules.DataBind();
display_modules.Visible = true;
}
}
private static DataTable GetData(string query, string user_id) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
cmd.Parameters.AddWithValue("#user_id", user_id);
sda.Fill(dt);
return dt;
}
private static DataTable GetDataSen(string query) {
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
And this is my ASP.net
<%# Page Title="All Modules" MasterPageFile="MasterPage.master" Language="C#" AutoEventWireup="true" CodeFile="~/all-modules.aspx.cs" Inherits="all_modules" %>
<asp:Content ContentPlaceHolderID="head" Runat="Server">
<script>
$(document).ready(function () {
//makes contains filter case insensitive
$.expr[":"].contains = $.expr.createPseudo(function (arg) {
return function (elem) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
//search has the user types
$('.search-box').keyup(function () {
var search_term = $(this).val();
if (search_term == "") {
//show all if nothing was entered
$('.project-link').removeClass('hide');
} else {
// hide all and then show only the search results
$('.project-link').addClass('hide');
$('.module-list *:contains("' + search_term + '")').closest('.project-link').removeClass('hide');
}
//check if any results were found
if ($('.project-link').not('.hide').length)
{
$('.no-results').addClass('hide');
} else {
$('.no-results').removeClass('hide');
}
});
});
</script>
</asp:Content>
<asp:Content ContentPlaceHolderID="menu" Runat="Server"></asp:Content>
<asp:Content ContentPlaceHolderID="main_content" Runat="Server">
<div class="row">
<div class="col-12">
<h1>All Modules</h1>
<h5 class="subheading">Search through a complete list of modules.</h5>
Add Modules
</div>
</div>
<div class="row">
<div class="col-12">
<div class="panel">
<h3>Search Modules:</h3>
<input type="text" class="search-box full-width" placeholder="Search via module name, code, course or lecturer" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="panel">
<asp:ListView ID="display_modules" runat="server" Visible="false">
<ItemTemplate>
<div class="project-link module-list">
<a href='<%# "module.aspx?module=" + Eval("module_id") %>'>
<p class="project-label"><%# Eval("course_name") %>
</p>
<asp:Label Text='
<%# Eval("module_id") + " - " %>' runat="server" CssClass="story-title" ID="Label1" />
<asp:Label Text='
<%# Eval("module_name") %>' runat="server" CssClass="story-title" ID="story_titleLabel" />
<span>
<p class="project-label"><%# Eval("f_name") + " " + Eval("l_name") %>
</p>
<div class="to-module"></div>
</a>
</div>
</ItemTemplate>
</asp:ListView>
<p class="hide no-results">No search results were found.</p>
</div>
</div>
</div>
</asp:Content>
Any idea why this might be happening? Any help would be greatly appreciated
I want to add the image to the database and display it in the grid view when it is added successfully. I coded everything, but when I add the details and press save the image is not displayed in the web page. I've attached screen shot for reference.
Here is the code that I used
.aspx code
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2">
<h2>Employee Details</h2>
</td>
</tr>
<tr>
<td>ID</td>
<td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Name</td>
<td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>BloodGroup</td>
<td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Emergency Contact No.</td>
<td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>
</tr>
<tr>
<td>Photo:</td>
<td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />
<asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />
<asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'
Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace Image_upload
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileuploadEmpImage.HasFile)
{
int length = fileuploadEmpImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadEmpImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
int id = Convert.ToInt32(txtID.Text);
string name = txtName.Text;
string bloodGroup = txtBloodGroup.Text;
string phoneNo = txtContactNo.Text;
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO database.employee (Id,Name,BloodGroup,PhoneNo,ImageI)" + "values('"+ txtID.Text +"', '"+ txtName.Text +"', '"+ txtBloodGroup.Text +"', '"+ txtContactNo.Text +"', '"+ fileuploadEmpImage.FileBytes +"')", connection);
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
txtID.Text = string.Empty;
txtName.Text = string.Empty;
txtBloodGroup.Text = string.Empty;
txtContactNo.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Record added successfully')", true);
BindGridData();
}
}
}
private void BindGridData()
{
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
MySqlCommand command = new MySqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,ImageI from database.employee", connection);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
grdEmployee.DataSource = dt;
grdEmployee.DataBind();
}
}
}
handler.ashx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace Image_upload
{
public class Employeeimage_handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
String myConnection = "datasource=127.0.0.1;port=3306;username=root;password=wafes123";
MySqlConnection connection = new MySqlConnection(myConnection);
connection.Open();
MySqlCommand command = new MySqlCommand("select ImageI from database.employee order by ID" + imageid, connection);
MySqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have an issue in your SQL statement that you use in the ASHX handler. First of all it produces an incorrect SQL statement and secondly it is vulnerable for SQL Injection attacks. See the OWASP Guidance for in depth technical explanation of the issue.
To fix your code introduce MySqlParameters:
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["Id"];
var connection = new MySqlConnection(
ConfigurationManager.ConnectionString["database"]);
connection.Open();
// remove the order by and add a where with a parameter placeholder
var command = new MySqlCommand(
"select ImageI from database.employee where id = #id",
connection);
// setup parameter and add to command
command.Parameters.AddWithValue("#id", imageid);
// execute
MySqlDataReader dr = command.ExecuteReader();
// rest of your code
}
Also move the connection string out of your code to the web.config. See the msdn article Connection Strings and Configuration Files
I am new to Asp.Net & C#. I am developing a blog. I am able to save images in a folder and the image path in SQL Server. Now I want to retrieve the image from folder whose path is stored in SQL Server table.
I try this:
ASPX markup:
<body>
<form id="form1" runat="server">
<div class="row">
<div class="page-header"></div>
<div class="col-lg-3">
<asp:Image ID="Image1" CssClass="img-thumbnail" runat="server" />
</div>
</div>
</form>
</body>
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace Admin_Panel
{
public partial class Admin : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
Image1.ImageUrl ="~/Images/" + filep;
}
con.Close();
}
}
}
But the above code will only show one image.
What I want: I want to show all images using a foreach loop or something like a loop, but I don't know how to do that.
Any help will be appreciated.
First of all, you should use asp.repeater:
<asp:Repeater ID="RptImages" runat="server">
<ItemTemplate>
<asp:Image ID="Img" runat="server" ImageUrl='<%# Container.DataItem %>'/>
</ItemTemplate>
</asp:Repeater>
Else:
public partial class Admin : System.Web.UI.Page
{
List<String> images = new List();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
images.add(String.Concat("~/Images/", filep);
}
con.Close();
RptImages.DataSource = images;
RptImages.DataBind();
}
}