ASPX ajax form post help - asp.net

Hey all, i have this peice of code that allows a user to select a jpg image, resize it and uploads it to the server driectory. The problem being is that it reloads the aspx page when it saves the image.
My question is-is there any way to do this same thing but with ajax so that it doesn't leave the page after submitting it? I've done this pleanty of times with classic asp pages but never with a aspx page.
Here is the code for the ASPX page:
<%# Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%>
<%# Import Namespace=System.Drawing %>
<%# Import Namespace=System.Drawing.Imaging %>
<%# Import Namespace=System.Drawing.Text %>
<%# Import Namespace=System %>
<%# Import Namespace=System.IO %>
<%# Import Namespace=System.Web %>
<%# Import Namespace=System.ServiceProcess %>
<%# Import Namespace=Microsoft.Data.Odbc %>
<%# Import Namespace=System.Data.Odbc %>
<%# Import Namespace=MySql.Data.MySqlClient %>
<%# Import Namespace=MySql.Data %>
<%# Import Namespace=System.Drawing.Drawing2D %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.ADO" %>
<%# Import Namespace=ADODB %>
<SCRIPT LANGUAGE="VBScript" runat="server">
const Lx = 200
const Ly = 60
const upload_dir = "/img/avatar/"
const upload_original = "tmpAvatar"
const upload_thumb = "thumb"
const upload_max_size = 256
dim fileExt
dim newWidth, newHeight as integer
dim l2
dim fileFld as HTTPPostedFile
Dim originalimg As System.Drawing.Image
dim msg
dim upload_ok as boolean
</script>
<%
Dim theID, theEmail, maleOrFemale
theID = Request.QueryString("ID")
theEmail = Request.QueryString("eMail")
maleOrFemale = Request.QueryString("MF")
randomize()
upload_ok = false
if lcase(Request.ServerVariables("REQUEST_METHOD"))="post" then
fileFld = request.files(0)
if fileFld.ContentLength > upload_max_size * 1024 then
msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
else
try
fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
if fileExt = ".jpg" then
originalImg = System.Drawing.Image.FromStream(fileFld.InputStream)
if originalImg.Height > Ly then
newWidth = Ly * (originalImg.Width / originalImg.Height)
newHeight = Ly
end if
Dim thumb As New Bitmap(newWidth, newHeight)
Dim gr_dest As Graphics = Graphics.FromImage(thumb)
dim sb = new SolidBrush(System.Drawing.Color.White)
gr_dest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
gr_dest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
gr_dest.DrawImage(originalImg, 0, 0, thumb.Width, thumb.Height)
try
originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat)
thumb.save(Server.MapPath(upload_dir & theID & fileExt), originalImg.rawformat)
msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
upload_ok = true
File.Delete(Server.MapPath(upload_dir & upload_original & fileExt))
catch
msg = "Sorry, there was a problem saving your avatar. Please try again."
end try
if not thumb is nothing then
thumb.Dispose()
thumb = nothing
end if
else
msg = "That image does not seem to be a JPG. Upload only JPG images."
end if
catch
msg = "That image does not seem to be a JPG."
end try
end if
if not originalImg is nothing then
originalImg.Dispose()
originalImg = nothing
end if
end if
%><head>
<meta http-equiv="pragma" content="no-cache" />
</head>
<html>
<script type="text/javascript" src="js/jquery-1.3.min.js"></script>
<form enctype="multipart/form-data" method="post" runat="server" id="sendImg">
<input type="file" name="upload_file" id="upload_file" style="-moz-opacity: 0; opacity:0; filter: alpha(opacity=0); margin-top: 5px; float:left; cursor:pointer;" onChange="$('#sendImg').submit();" >
<input type="submit" value="Upload" style="visibility:hidden; display:none;">
</form>
</body>
</html>
Any help would be great! :o)
David

ajax and <input type="file"> don't work well together. the underlying XMLHttpRequest object is restricted and can't actually access the file upload. There is a very limited set of things that you can do with any javascript as it pertains to the file upload. The easiest way to fake what you are trying to do is use an iframe.

Related

CS0117: 'System.Data.DataSet' does not contain a definition for 'GetXML'

Below is the code that is causing the error. As a newbie to XSL and ASP.NET, I don't quite understand why the error is occurring...
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="view.aspx.cs" Inherits="ININ.Marquee.Web.view" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Configuration" %>
<%# Import Namespace="System.Xml" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Xml.XPath" %>
<%# Import Namespace="System.Xml.Xsl" %>
<!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" >
<html>
<head>
</head>
<body>
<form id="form1" runat="server" >
<div>
<script runat="server">
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
public static string GetHtml(string xsltPath, string xml)
{
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(xml));
XPathDocument document = new XPathDocument(stream);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltPath);
transform.Transform(document, null, writer);
return writer.ToString();
}
public string details = string.Empty;
private void Page_Load(object sender, EventArgs e)
{
/******** - This the START of all the Database Stuff - ********/
// Create a String to hold the database connection string.
// NOTE: Put in a real database connection string here or runtime won't work
string sdwConnectionString = #"Data Source = server; user id=username; password=password; Initial Catalog = database;";
// Create a connection
SqlConnection sdwDBConnection = new SqlConnection(sdwConnectionString);
// Open the connection
sdwDBConnection.Open();
// Create a String to hold the query.
string query = "SELECT * from IWrkgrpQueueStats WHERE ((substring(convert(char,dIntervalStart,120),1,10) = substring(convert(char,getdate(),120),1,10)) AND (cName IN ('Password','Arbour/CMBS/Other','Incident Escalation', 'OPOM/SOS/MyAccount','PC/Outlook','Overflow')) AND (cReportGroup='*' AND cHKey3='*' AND cHKey4='*'))";
// Create a SqlCommand object and pass the constructor the connection string and the query string.
SqlCommand queryCommand = new SqlCommand(query, sdwDBConnection);
// Use the above SqlCommand object to create a SqlDataReader object.
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Create a DataTable object to hold all the data returned by the query.
DataTable duplicatedataTable = new DataTable();
// Use the DataTable.Load(SqlDataReader) function to put the results of the query into a DataTable.
duplicatedataTable.Load(queryCommandReader);
// Open the connection
sdwDBConnection.Close();
DataSet ds = new DataSet("interactions");
ds.Tables.Add(duplicatedataTable);
string XML = ds.GetXML();
details=GetHtml(Server.MapPath("~/Test.xsl"), XML);
}
</script>
<table width="100%">
<tr>
<td align="left">
<table width="100%" border="0">
<tr bgcolor="Silver">
<th align="center">
<%= details %>
</th>
</tr>
</table>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I have reviewed both this code and the .xsl code and there doesn't appear to be any issues. Can anyone please explain what the error means and where the issue causing the error would occur? Thanks for your assistance.
I believe your problem is one of case-sensitivity.
Why don't you try:
string XML = ds.GetXml();
rather than
string XML = ds.GetXML();
Hope that helps.

classic asp to asp.net conversion

hi i am working on project jigsaw puzzle game . i have done with coding in classic asp using vb script and it working properly . i want to do same coding asp.net using vb.net but css style i was written it was not working properly in asp.net can anybody help me doing this conversion.
<html>
<head>
<script type="text/javascript">
function setText(pieceID)
{
if (document.getElementById("first").value == '' )
{
document.getElementById("first").value=pieceID;
}
else
{
document.getElementById("second").value=pieceID;
document.swap.submit();
}
}
</script>
</head>
<body>
<%
dim img
img = "img1.jpg"
%>
<div class="classname"> <img src="<%response.write img%>"> </div>
<%dim imgPIX
imgPIX = 60
%>
<style>
.icons { display: block; width: <%response.write imgPIX%>px; height: <%response.write imgPIX%>px; background-image: url(<%response.write img%>); background-repeat: no-repeat; }
<%
dim proper
dim ico_number,col
dim row_number,rw
for row_number = 1 to 6
rw = (row_number - 1) * (-1 * imgPIX)
for ico_number = 1 to 6
col = (ico_number - 1) *(-1 * imgPIX)
response.write ".icon"& row_number &"_"& ico_number &" { background-position: col &"px "& rw &"px; } "
if not proper = "" then
proper = proper & "," & row_number &"_"& ico_number
else
proper = row_number &"_"& ico_number
end if
response.write ".icon"& row_number &"_"& ico_number &" { background-position: 0px 0px; } "
next
next
%>
</style>
<%
dim userfeed
if request.form("userform") = "" then
userfeed = random_sort(proper)
end if
if request.form("first") <> "" and request.form("second") <> "" then
userfeed = request.form("userform")
userfeed = replace(userfeed,request.form("first"),"temp1")
userfeed = replace(userfeed,request.form("second"),"temp2")
userfeed = replace(userfeed,"temp1",request.form("second"))
userfeed = replace(userfeed,"temp2",request.form("first"))
end if
%>
<center>
<form name="swap" action="default.asp" method="post">
<input type="hidden" name="first" ID="first">
<input type="hidden" name="second" ID="second">
<input type="hidden" name="userform" ID="userform" value="<%response.write userfeed%>">
</form>
<table border="0">
<%
if userfeed = proper then
%>
<H1>Solved !!</h1>
<%
end if
dim icoarr
icoarr = split(userfeed,",")
dim ctr
ctr =0
for each piece in icoarr
if ctr =6 then
response.write "<tr>"
end if
%>
<td><span class="icons icon<%response.write piece%>" style="float:left;" onclick="setText('<%response.write piece%>')"></span></td>
<%
if ctr =6 then
ctr =1
else
ctr = ctr + 1
end if
next
%>
<%public function random_sort(arrySTR)
arrySTR = arrySTR & ","
dim retstr
do while arrySTR <> ""
dim arr
arr = split(arrySTR,",")
dim random_number
randomize
random_number=int(rnd*(ubound(arr)-1))+0
'response.write random_number
retstr =arr(random_number) & "," & retstr
arrySTR = replace(arrySTR,arr(random_number) & ",","")
loop
retstr = mid(retstr,1,len(retstr)-1)
'response.write "<br>" & retstr
random_sort=retstr
end function
%>
</table>
</body>
You can try Asp.Net WEBMATRIX tool for converting the same code to Asp.Net with minimal effort
http://www.asp.net/web-pages

Display only one image in a div

I want to display an image that I loop it from the folder.
<div class="blah">
<% System.IO.FileInfo[] files = new System.IO.DirectoryInfo(Server.MapPath("/MyPath/"))
.GetFiles();
var exefiles = from System.IO.FileInfo f in files
where f.Extension == ".jpg" ||f.Extension == ".jpeg"
|| f.Extension == "JPG"
select f;
foreach (System.IO.FileInfo f in exefiles) { %>
<img src="blahblah.jpg" />
<% } %>
</div>
Problem : The div display all the images that store in the folder.
But I want to display only 1 image in my div.
Thank you so much.
Should be able to do this with Directory.GetFiles Method (String, String) (System.IO)
something like:
<div class="blah">
<%
string path = "images/";
string[] files = System.IO.Directory.GetFiles(Server.MapPath(path), "*jp*g");
if (files.Length > 0) { %>
<img src="<%= path + System.IO.Path.GetFileName(files[0])%>" />
<% } %>
</div>
You shouldn't have any login inside your view, that's why it's called Model View Controller. Put your logic inside the Action and pass it to the view inside the model or the ViewBag.

ASP.net mvc how to comment out html code in page

Is there an easy way to comment out a loop which renders some html and has inline html without deleting anything? I am copying and pasting some code from another project to rebuild a new public front end from a working internal backend.
Below is an example of a sitation in which it would be nice...in asp.net MVC 2
<%
List<VehicleBodyTypeListItem> lstBodyTypes = (List<VehicleBodyTypeListItem>)ViewData["ddBodyType"];
foreach (VehicleBodyTypeListItem bodyType in lstBodyTypes)
{
%>
<a href="<%= Url.Action( "Search", new { BodyTypeID=bodyType.BodyTypeID, BodyType= Url.Encode( Html.WebLinkify( bodyType.BodyType))}) + (string)ViewData["httpCriteria"] %>">
<%= Html.Encode( String.Format( "{0} ({1})", bodyType.BodyType, bodyType.Count.ToString())) %> </a>
<br />
<%
}
%>
I have not completed the method that populates this list yet, and have about 5 more like it further down the page.
The keyboard shortcut is, if you select the section you want commented out is: CTRL + K + C will comment out code. CTRL + K + U will uncomment the code.
Comment a block of code by enclosing it in #* and *#
Do you mean adding comments to the code. If so you just need to add //. Like here:
<%
List<VehicleBodyTypeListItem> lstBodyTypes = (List<VehicleBodyTypeListItem>)ViewData["ddBodyType"];
foreach (VehicleBodyTypeListItem bodyType in lstBodyTypes) // Here there's a comment
{
%>
<a href="<%= Url.Action( "Search", new { BodyTypeID=bodyType.BodyTypeID, BodyType= Url.Encode( Html.WebLinkify( bodyType.BodyType))}) + (string)ViewData["httpCriteria"] %>">
<%= Html.Encode( String.Format( "{0} ({1})", bodyType.BodyType, bodyType.Count.ToString())) %> </a>
<br />
<%
}
%>

Using webform user control on webform in MVC Project

I am using a server control on a single web.forms page. I have to use this control on a web.forms page since its a server control, although this is actually a MVC project. So I created a web.forms folder and put my new page in it. I then copy the example code from the signature control. I get the following error:
The base class includes the field 'ctrlSign', but its type (WebSignatureCapture.SignatureControl) is not compatible with the type of control (ASP.signaturecapture_signaturecontrol_ctlsignature_ascx).
I know the code works because if I removed the ID attribute from the server control, it no longer gives me this error and my control renders. But I need the attribute for the ID so I can perform is post event... Any ideas why?
I am using this signature control. Here's the web.forms code...
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="KahunaCentralTIDRevamp.SignatureCapture.Index" %>
<%# Reference Control="~/SignatureCapture/SignatureControl/ctlSignature.ascx" %>
<%# Register TagPrefix="uc" TagName="Signature" Src="~/SignatureCapture/SignatureControl/ctlSignature.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Signature Application Demo</title>
</head>
<body>
<form id="frmOrder" method="post" runat="server">
<div>
Please Sign Below:
</div>
<div>
<uc:Signature ID="ctrlSign" SignHeight="150" SignWidth="300" SignatureCodePath="~/SignatureCapture/SignatureControl/"
SavePath="~/SignatureCapture/" SignatureFileFormat="Gif" runat="server" />
<%-- <uc:Signature id="ctlMySignature" PenColor="Red" PenWidth="2" BackColor="Yellow" SignWidth="300" SignHeight="150"
SavePath="~/Signatures/" SignatureCodePath="~/SignatureControl/" SignatureFileFormat="Gif" Runat="server"></uc:Signature>--%>
</div>
<div>
<input type="button" value=" Re-Sign " onclick="ClearSignature();">
<asp:Button runat="server" ID="btnSave" Text=" Save " onmousedown="document.getElementById('btnSave').value = 'Wait...';"
OnClientClick="DirectSave();" OnClick="btnSave_Click" />
</div>
</form>
<script language="javascript" type="text/javascript">
// This is the method that is directly called, this will save signature
// and then call server code to do further processing. You can change
// the delay of 5 seconds as per your needs
function DirectSave() {
SaveSignature();
var date = new Date();
var curDate = null;
// delay of 5 seconds, 5000 milisecons, change as per requirement
do { curDate = new Date(); }
while (curDate - date < 5000);
return true;
}
</script>
</body>
</html>
Open the .ascx markup file of the user control. It should read something like this:
<%# Control
Language="C#"
AutoEventWireup="true"
CodeFile="ctlSignature.ascx.cs"
Inherits="WebSignatureCapture.SignatureControl.ctlSignature" %>
Modify it to:
<%# Control
Language="C#"
AutoEventWireup="true"
CodeBehind="ctlSignature.ascx.cs"
Inherits="WebSignatureCapture.SignatureControl.ctlSignature" %>
Notice CodeFile -> CodeBehind.
Someone I know had a similar problem a while back, and then they found something that they could do something in the BeginRequest which sorted his problem and allowed him to use server controls in views. I did a quick search for it, and I believe that this is what he used.
Code below:
void Application_BeginRequest(object sender, EventArgs e)
{
var form = HttpContext.Current.Request.Form;
form.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(form, false, null);
// Refinement 1:
foreach (var key in form.AllKeys.Where(key => key.Contains("$")))
{
var value = formkey;
form.Remove(key);
var newKey = key.Substring(key.LastIndexOf("$") + 1);
form.Add(newKey, value);
}
}

Resources