Ajax AutoCompleteExtender not hitting code behind in userControl C# - c#

I'm trying to use the Ajax autoCompleteExtender to auto complete my textboxes using a sql query in my code behind. The problem I'm having is that my code behind isn't being hit at all.
What happens instead is my autocomplete options display as the code from my masterpage.
I've done some research and the problem might be that my textboxes are in an ascx file called from my aspx file but I can't figure out a way around it. I've even tried pointing the ServicePath to a webService and it still doesn't hit.
Any input would help, thank you!
Here's my relevant code:
Aspx File:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/Admin.Master" AutoEventWireup="true" EnableEventValidation="false" %>
<%# Register TagPrefix="AdminSearch" TagName="AdminSearch" Src="AdminSearch.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<AdminSearch:AdminSearch runat="server" ID="AdminSearch" />
</asp:Content>
Ascx File:
<%# Control Language="C#" ClassName="WebUserControl" AutoEventWireup="true" EnableViewState="true" Inherits="AdminSearch" CodeBehind="AdminSearch.ascx.cs" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<link href="../Style/Search/AdminSearch.css" rel="stylesheet" />
<script src="../Scripts/js/Search/AdminSearch.js"></script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true">
</asp:ScriptManager>
<td class="g3">
<br />
<asp:TextBox ID="TextBoxTierProfile" CssClass="g3" runat="server"></asp:TextBox><br />
<cc1:AutoCompleteExtender ServiceMethod="SearchProfiles" ServicePath="~/AutoComplete.asmx"
MinimumPrefixLength="2"
CompletionInterval="1" EnableCaching="true" CompletionSetCount="10"
TargetControlID="TextBoxTierProfile"
ID="AutoCompleteExtender2" runat="server" FirstRowSelected="false">
</cc1:AutoCompleteExtender>
</td>
Asmx File:
using System.Collections.Generic;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
namespace InternalTools.Admin.Search
{
/// <summary>
/// Summary description for AutoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
static string sConnection;
public AutoComplete()
{
if (HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString().Contains("127.0.0.1"))
{
sConnection = ConfigurationManager.ConnectionStrings["Reporting"].ToString();
}
else
{
sConnection = ConfigurationManager.ConnectionStrings["live"].ToString();
}
}
[System.Web.Script.Services.ScriptMethod]
[WebMethod]
public static string[] SearchProfiles(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = sConnection;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = (I've cut out the query for security reasons)
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> profiles = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
profiles.Add(sdr["PROFILENAME"].ToString());
}
}
conn.Close();
return profiles.ToArray();
}
}
}
}
}

Related

GETTING ERROR IN SIGN UP PAGE for inserting values in SQL server DATABASE table through webform TEXTBOX

hi I am trying to make a log in page as well as sign up page in asp.net using 3 tier architecture by using sql server architecture. I am able to fetch data from sql server data base which I have manually inserted during table creation in database and I am able to use it in my log in page.
I have also created a sign up page but I am not able to get the values from sign up webform textbox to sqlserver database I am getting some error kindly help me with this.
I have given the connection string of sql server in web.config
my sql server table creation code
CREATE TABLE LOGINDETAILS
(USERID VARCHAR(50),
PASSWORD VARCHAR (50)
);
INSERT INTO LOGINDETAILS (USERID,PASSWORD) values( 'sam', 'pass');
web.config connection string code
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="DBcon" connectionString="Data Source=P3A-B1YH882\SQLSERVER;Initial Catalog=master;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
my business layer /middle layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using DataAcess;
using System.Data.SqlClient;
using System.Data.Sql;
namespace middlelayer
{
public class UserBO
{
private string _UserName = " ";
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private string _Password = " ";
public string Password
{
get { return _Password; }
set { _Password = value; }
}
DataA da = new DataA();
public bool getUser()
{
if (da.IsValid(UserName, Password).Tables[0].Rows.Count == 0)
{
return false;
}
else
{
return true;
}
}
}
}
my datAccess layer code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace DataAcess
{
public class DataA
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
public DataSet IsValid(string UserName, string Password)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM LOGINDETAILS WHERE USERID ='" + UserName + "' and PASSWORD= '" + Password + "'", con);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
return ds;
}
}
}
MY LOGIN PAGE CODE
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="WebApplication4.login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 277px">
<form id="form1" runat="server">
<div>
<asp:Label ID="lbluserid" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Height="17px" Text="User ID" Width="52px"></asp:Label>
<asp:TextBox ID="txtuserid" runat="server" BackColor="#99FFCC" style="margin-left: 122px"></asp:TextBox>
<br />
</div>
<p>
<asp:Label ID="lblpassword" runat="server" BackColor="#FFFF99" BorderStyle="Ridge" Text="Password"></asp:Label>
<asp:TextBox ID="txtpassword" TextMode="Password" runat="server" BackColor="#99FFCC" style="margin-left: 110px" ></asp:TextBox>
</p>
<p>
</p>
<asp:Button ID="btnlogin" runat="server" BackColor="#33CCFF" BorderStyle="Ridge" OnClick="btnlogin_Click" style="margin-left: 78px" Text="Login" Width="107px" />
<p>
</p>
<asp:Label ID="Label1" runat="server" Text="NOT REGISTERED ??"></asp:Label>
<asp:HyperLink ID="HyperLink1" runat="server" BorderStyle="Outset" NavigateUrl="~/sign_up.aspx">SIGN UP</asp:HyperLink>
</form>
</body>
</html>
* MY SIGN UP PAGE CODE*
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="sign_up.aspx.cs" Inherits="WebApplication4.sign_up" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="lblssignup" runat="server" BackColor="#FF99CC" Text="SIGN UP"></asp:Label>
<br />
<br />
<p>
<asp:Label ID="lblsuserid" runat="server" Text="ENTER USER ID"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" style="margin-bottom: 0px"></asp:TextBox>
</p>
<asp:Label ID="lblspassword" runat="server" Text="ENTER PASSWORD"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Width="66px" />
</p>
</form>
</body>
</html>
SIGN UP PAGE BUTTON CODE FOR ENTERING DATA INTO SQL SERVER DATABASE ON BUTTON CLICK
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.SqlClient;
using System.Data;
using middlelayer;
namespace WebApplication4
{
public partial class sign_up : System.Web.UI.Page
{
string conString = ConfigurationManager.ConnectionStrings["DBcon"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES ('" +TextBox1.Text+ "' , '" +TextBox2.Text+ "')";
SqlCommand com = new SqlCommand(ins,con);
DataSet du = new DataSet();
SqlDataAdapter sdi = new SqlDataAdapter(com);
sdi.Fill(du);
con.Close();
}
}
}
I AM getting error in this last code only of sign up button it is not able to insert values of SIGN UP webform Textbox to sql server databse table and also not reflecting the real values which I want to add in sql server TABLE using sign up webform and also noty saving it. It is sending some error values . kindly help me with this.
BELOW ARE THE IMAGES OF LOG IN AS WELL AS SIGN UP PAGE FOR REFERENCE
LOGIN PAGE WEB FORM
SIGN UP PAGE WEBFORM
KINDLY HELP IN RESOLVING THIS ISSUE
Try this:
SqlConnection con = new SqlConnection(conString);
con.Open();
string ins= "Insert into [LOGINDETAILS](USERID, PASSWORD) VALUES (#param1 , #param2)";
SqlCommand cmd = new SqlCommand(ins,con);
cmd.Parameters.Add("#param1", SqlDbType.Varchar, 50).value = TextBox1.Text;
cmd.Parameters.Add("#param2", SqlDbType.Varchar, 50).value = TextBox2.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close()

asp using master page variable in content page

I've read every post I can find on how to do this and tried them all. I have a Master page called DNAStaff (at root) containing:-
<%# Master Language="C#" AutoEventWireup="true" CodeFile="DNAStaff.master.cs" Inherits="DNAStaff" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link href="~/Styles/DNA.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
...............
</div>
</form>
</body>
</html>
The Masterpage code behind includes:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Data;
public partial class DNAStaff : System.Web.UI.MasterPage
{
public string MyAccessLevel
{
get; set;
}
protected void Page_Load(object sender, EventArgs e)
{
string ConnectionString = "Data Source=NZ1;Initial Catalog=Intranet;Integrated Security=false;UID=IntranetAccess;PWD=*****";
string sqlstring = #"select [MenuID], [Item], Target, SecLevel from [MENUS] ";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataReader rdr = null;
int MainGroup;
try
{
if (Request.Cookies["userinfo"] != null)
{
MyAccessLevel = Server.HtmlEncode(Request.Cookies["userinfo"]["accessLevel"]);
}
else
{
MyAccessLevel = "1";
}
.........
The content page includes:
<%# Page Title="" Language="C#" MasterPageFile="~/DNAStaff.master" AutoEventWireup="true" CodeFile="main.aspx.cs" Inherits="main" %>
<%# MasterType virtualpath="~/DNAStaff.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
Set Primary Project
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>
enter code here
and the content page code behind contains:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class main : System.Web.UI.Page
{
string AccessLevel = "";
protected void Page_Load(object sender, EventArgs e)
{
AccessLevel = Master.MyAccessLevel;
TextBox1.Text = AccessLevel;
}
}
The line "AccessLevel = Master.MyAccessLevel" gives an error:-
Error CS1061 'MasterPage' does not contain a definition for
'MyAccessLevel' and no extension method
'MyAccessLevel' accepting a first argument of type 'MasterPage' could be
found (are you missing a using directive or an assembly reference?)
8_Live_main.aspx D:\Development\dnanew.steelpencil.com\Live\main.aspx.cs
13 Active
I want to set the variable MyAccessLevel in the MasterPage at load and read it in any content page. I'm obviously missing something, can someone please help?
You can access the Master Page like this.
Site1 master = ((Site1)(Page.Master));
TextBox1.Text = master.AccessLevel;
Where Site1 is the class name of the Master Page (public partial class Site1 : System.Web.UI.MasterPage)
However you should know that the Master Page_Load is initialized at a later stage in the Page Life Cycle than the Page. So when you access the value of AccessLevel, it will always be empty.
See https://msdn.microsoft.com/en-us/library/dct97kc3.aspx
As in the content page already you have assigned the MasterType like below.
<%# MasterType virtualpath="~/DNAStaff.master" %>
So now your child/content page can able to use/access the master layout including the public variable/properties defined in the master page.
So now, as per your requirement, to access the public property(AccessLevel) defined in your master page and assign to the child/content page textbox, you need to write the below code
Site myMaster = ((Site)(Page.Master));
TextBox1.Text = myMaster .AccessLevel;
Hope it solves your problem.
Here are the more references about Master page and accessing the contents of master page
https://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
https://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx
This post should answer your question.You must add
<%# MasterType VirtualPath="~/your page path" %>
directive to your page

Autocompletebox not calling Webmethod and pop for not displaying properly

I am trying to use autocompletebox using ajaxToolkit autpcompleteExtender. I refer this link http://www.aspdotnet-suresh.com/2011/05/ajax-autocompleteextender-sample.html .But now I am facing two problems.
Its working fine when I use webmethod on code behind but when I try to use it from seperate webservice file its not calling their webmethod. For this I set service path also but its not working. Please check the code
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Curriculam_Mapping.WebForm2" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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>
<cc1:ToolkitScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<asp:TextBox ID="txtClass" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtClass" ServiceMethod="GetCountry" ServicePath="WebService1.asmx" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" >
</cc1:AutoCompleteExtender>
</div>
</form>
</body>
</html>
.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
namespace Curriculam_Mapping
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
// 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 WebService1 : System.Web.Services.WebService
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetClass(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Select Class_Id,Title from Mst_Class where Title like #Name+'%'", con);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> ClassNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ClassNames.Add(dt.Rows[i][2].ToString());
}
return ClassNames;
}
}
}
When I use webmethod on code behind its work fine but popup not displaying properly.Its not attach to textbox control. Please check this image file
Please help me for solving this problem.
thank you.
but popup not displaying properly
This could be it is not getting the proper css for the pop-up.
Here is a link which has more about that
http://vijaysinghnegi.blogspot.in/2012/04/best-css-style-for-autocomplete.html
http://www.dotnetfox.com/articles/custom-css-style-for-ajax-autocomplete-extender-1115.aspx
Similar question on SO
A nice css style for ajax autoComplete Extender
Edit 1
Try to uncomment this line
// [System.Web.Script.Services.ScriptService]
Basically this method will be called through script and you have not allowed it to be called by java-script or jQuery.
So your code should be follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
namespace Curriculam_Mapping
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
// 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 WebService1 : System.Web.Services.WebService
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetClass(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Select Class_Id,Title from Mst_Class where Title like #Name+'%'", con);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> ClassNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ClassNames.Add(dt.Rows[i][1].ToString());
}
return ClassNames;
}
}
}
I got solution, just remove static keyword from web-method and its working,I don't know its a proper way or not but its working for me.
thank you for help.

ASP.NET SlideShowExtender retrieving images from web service, but doing nothing when executed

So on my ASP.NET solution's default page, I have a SlideShowExtender object, linked to a WebMethod which retrieves slides from an MSSQL database. Through debugging I can confirm that Slide objects are successfully created from said database, but once the page has loaded the SlideShow element does nothing.
Below is my code; I appreciate in advance any responses received. Thank you.
Edit: I forgot to mention that I've have verified the integrity of the Image URLs; they're correct.
Default.aspx (Default.aspx.cs is just a standard code-behind with an empty Page_Load method):
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="Dissertation._Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ToolkitScriptManager ID="scrptman" runat="server"></asp:ToolkitScriptManager>
<asp:Image ID="imgBanner" Width="800" Height="300" runat="server"/>
<br />
<asp:Label ID="lblDesc" runat="server"></asp:Label>
<asp:SlideShowExtender ID="sldShow" runat="server"
TargetControlID="imgBanner"
SlideShowServicePath="~/BannerImages.asmx"
SlideShowServiceMethod="GetPhotos"
AutoPlay="true"
ImageDescriptionLabelID="lblDesc"
Loop="true" />
</asp:Content>
BannerImages.asmx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using AjaxControlToolkit;
namespace Dissertation
{
/// <summary>
/// Summary description for BannerImages
/// </summary>
///
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class BannerImages : System.Web.Services.WebService
{
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public Slide[] GetPhotos()
{
List<Slide> images = new List<Slide>();
ConnectionStringSettings settings = System.Configuration.ConfigurationManager.ConnectionStrings["Database"];
SqlConnection conn = new SqlConnection(settings.ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from sol_bannerData", conn);
SqlDataReader read = null;
try
{
conn.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
images.Add(new Slide(Server.MapPath("~/cms/uploads/banners/" + read["ImageURL"].ToString()), "", read["Description"].ToString()));
}
}
catch(SqlException err)
{
images.Clear();
images.Add(new Slide("", "", "Images could not be loaded: " + err.Message));
return images.ToArray();
}
finally
{
if(read != null) read.Close();
if(conn != null) conn.Close();
}
Slide[] toReturn = images.ToArray();
return toReturn;
}
}
}
Problem solved; I used jquery.cycle.all instead.

The connection was reset in Upload Telerik

I code a example like telerik Upload demo but have the following error when submit(in FF):
The connection was reset.
The demo of telerik RadUpload is here
This is the code of .aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage1.master" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Main_Upload" %>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<title>Upload file</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<telerik:RadScriptManager ID="rsmScriptManager" runat="server">
</telerik:RadScriptManager>
<telerik:RadProgressManager ID="rpmUploadFile" runat="server" />
<div style=" color:Green">Valid files(*.doc, *.docx, *.xls, *.xlsx, *.pdf)</div>
<telerik:RadUpload ID="rulFiles" runat="server" InitialFileInputsCount="2" MaxFileInputsCount="5" AllowedFileExtensions=".doc,.docx,.xls,.xlsx,.pdf">
</telerik:RadUpload>
<telerik:RadProgressArea runat="server" ID="rpaUpload"></telerik:RadProgressArea>
<asp:Button ID="btnUpload" runat="server" Text="Ok" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblNoResults" runat="server" Visible="True">No uploaded file!</asp:Label>
<asp:Repeater ID="rptValidResults" runat="server" Visible="false">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"FileName") %>(<%#DataBinder.Eval(Container.DataItem,"ContentLength").ToString() + " bytes" %>)<br />
</ItemTemplate>
</asp:Repeater>
<div style="color: red; padding-top: 40px;">Invalid files:</div>
<asp:Label id="lblNoInvalidResults" runat="server" Visible="True">No invalid files.</asp:Label>
<asp:Repeater ID="rptInvalidResults" runat="server" Visible="false">
<ItemTemplate>
File: <%#DataBinder.Eval(Container.DataItem,"FileName") %>(<%#DataBinder.Eval(Container.DataItem,"ContentLength").ToString() + " bytes" %>)<br />
Mime-type: <%#DataBinder.Eval(Container.DataItem,"ContentType") %>
</ItemTemplate>
</asp:Repeater>
And the code behind in *.cs file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
public partial class Main_Upload : System.Web.UI.Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
BindValidResult();
BindInvalidResult();
}
private void BindValidResult()
{
if(rulFiles.UploadedFiles.Count > 0)
{
foreach (UploadedFile validFile in rulFiles.UploadedFiles)
{
var targetFolder = Server.MapPath(Commons.PAGER.UPLOAD_FOLDER);
validFile.SaveAs(Path.Combine(targetFolder,validFile.GetName()),true);
}
lblNoResults.Visible = false;
rptValidResults.Visible = true;
rptValidResults.DataSource = rulFiles.UploadedFiles;
rptValidResults.DataBind();
}
else
{
lblNoResults.Visible = true;
rptValidResults.Visible = false;
}
}
private void BindInvalidResult()
{
if(rulFiles.InvalidFiles.Count > 0)
{
lblNoInvalidResults.Visible = false;
rptInvalidResults.Visible = true;
rptInvalidResults.DataSource = rulFiles.InvalidFiles;
rptInvalidResults.DataBind();
}
else
{
lblNoInvalidResults.Visible = true;
rptInvalidResults.Visible = false;
}
}
}
Thanks!!!!
I'll go ahead and tell you with almost 100% certainty that the line that is causing this is:
var targetFolder = Server.MapPath(Commons.PAGER.UPLOAD_FOLDER);
It could be that you do not have permission to connect the server, or a variety of other issues.
To test this change "var targetFolder" to something like:
var targetFolder = #"C:\Users\j\Desktop\TEMP\"
Run this and it works perfectly, hence the idea that the path you're trying to access on the server is the problem.
Perhaps you should specify the path if possible. For example, if you are on a domain:
var targetFolder = #"\\server\Users\"
This would access that server and then the users folder therein that I have on my domain.

Categories

Resources