I am using the jQuery AjaxForm plugin
to create an preview of an image I the user select to load to the server.
I use an Http Handler to create an temp image file that is used for the image preview.
In response to client side 'onchange' event of the FileUpload control the image preview is created successfully.
I have a button that sends the whole form (UploadImageToServerStep1.aspx) to the server. In the server side Click event of that button I try to transfer the control to another page (UploadImageToServerStep1.aspx2),the control gets to the other page code behind file(The control gets to that page Page_Load event) but the page is not displayed - instead the referring page is displayed(UploadImageToServerStep1.aspx)again (the control do not go the page load event of that page).
The JS code in UploadImageToServerStep1.aspx is :
< script type = "text/javascript" >
var preview = {
ImagePreview: function(imageId) {
var formId = '<%= Form.ClientID %>';
var fileUploadId = '<%= FileUpload1.UniqueID %>';
var action = $('#' + formId).attr('action');
var imageName = $("input[serverId = 'FileUpload1']").val();
$('#' + formId).attr('action', './HttpHandlers/ImagesHandler.ashx?action=imagePreview&f=' + fileUploadId + '&i=' + imageName);
$('#' + formId).ajaxForm(function() {
$('#' + imageId).attr('src', './HttpHandlers/ImagesHandler.ashx?action=imagePreview&f=' + fileUploadId + '&i=' + imageName);
$('#' + imageId).show();
$('#' + formId).attr('action', action);
});
$('#' + formId).submit();
}
}; < /script>/
In UploadImageToServerStep1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FileUpload1.Attributes.Add("onchange", "preview.ImagePreview('htmlImgPreview');");
FileUpload1.Attributes.Add("serverId", "FileUpload1");
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("UploadImageToServerStep2.aspx");
//Server.Transfer("UploadImageToServerStep2.aspx");
}
}
In the HttpHandler :
case "imagePreview":
string f = context.Request.QueryString.Get("f");
string i = context.Request.QueryString.Get("i");
const string uploadImageTempPath = "~/Images/TempImages/";
if (!string.IsNullOrEmpty(context.Request.QueryString.Get("i")) && context.Request.Files[f] != null)
{
HttpPostedFile file = context.Request.Files[f];
SaveImage(context, file, uploadImageTempPath, i);
}
context.Response.ContentType = GetContentType(context.Session["fileName"].ToString());
if (context.Session["fileName"] == null || context.Request["i"] == null)
{
return;
}
byte[] byteArray1 =
System.IO.File.ReadAllBytes(
context.Request.MapPath(string.Format("{0}{1}", uploadImageTempPath, context.Session["fileName"])));
context.Response.BinaryWrite(byteArray1);
break;
}
Can someone please write what is the cause for that behavior and how can I solve this problem
Thanks
When trying to do a response.redirect in response to an ajax call, your browser is not going to behave in the same way it would with a regular synchronous request. You can however, take the response and do something with it on the JS side. I believe this will help you.
Returning redirect as response to XHR request
Related
I am working on ASP.NET ajax_uploadfile here I need to show a error message I had given AllowedFileTypes="jpg,jpeg,png"
Here is my code:
<asp:AjaxFileUpload runat="server" ThrobberID="Throbber"
ID="upFile" AllowedFileTypes="pdf" Onchange="Callingerrormesage()"
MaximumNumberOfFiles="5" OnClientUploadComplete="File_Upload" />
Here is my script code:
<scrpt>
function Callingerrormesage(){
alert(1);
}
</script>
Here is my code behind:
protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{
string filename = e.FileName;
string strDestPath = Server.MapPath("~/Documents/");
AjaxFileUpload1.SaveAs(#strDestPath + filename);
}
when I uploaded the jpeg file it's working fine when I need to upload the other than the jpeg file
I need to show the error message like
I had given Onchange="Callingerrormesage()" not working could you please help me on this?
You should validate BEFORE uploading like this:
$("input:file").change(function () {
if ($(this).val() !== "") {
var ul_file = $(this).val();
var extension = ul_file.substr((ul_file.lastIndexOf('.') + 1));
var accepted_file_endings = ["jpg", "jpeg"];
extension = extension.toLowerCase()
if ($.inArray(extension, accepted_file_endings) !== -1) {
...
//send file
protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{
string filename = e.FileName;
string strFileExtension = System.IO.Path.GetExtension(strLongFilePath);
if(strFileExtension=="jpg")
{
Your code here
}
else
{
session["error"]="Your error message";
}
and retrive the session value at your page...
Let me explain my project first of all.
Its a form with some information that I add in to textboxs and a signature field.
When you click on the signature it redirects you to another page where you sign and then goes back to the form and puts the signature in an image.
Point is when I go to the signature page I put the Form information in to a cookie so I can put them back on when I return from the signature page.
The problem is when it gets to the other page the cookie gets messed up content wise. If I try to write some simple hebrew on the page there is no problem.
This is the code that saves the cookie.
protected void ReCapture(object sender, EventArgs e)
{
string s = "";
foreach (Control c in form1.Controls)
{
if (c.GetType() == typeof(TextBox))
{
s += ((TextBox)c).Text + ":" + ((TextBox)c).ID + ",";
}
if (c.GetType() == typeof(Image))
{
s += ((Image)c).ImageUrl + ":" + ((Image)c).ID + ",";
}
}
Response.Cookies.Remove("Controls");
HttpCookie hc = new HttpCookie("Controls",s.Remove(s.Length - 2));
hc.Expires.AddHours(2);
hc.Path = "/";
Response.Cookies.Add(hc);
Response.Redirect("SignaturePage.aspx?id=" + ((Control)sender).ID);
}
This is the signature page code(practically nothing)
protected void Save(object sender, EventArgs e)
{
Session["TheSignature"] = Request.Form["TheData"];
Response.Redirect("Test.aspx");
}
Why is this happening?
I have referenced my javascript in my page as follows
<script src="JScript1.js" type="text/javascript"></script>
These are my function inside that script file
function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}
function f(sender, args) {
args.IsValid = false;
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
var txt = gridview.getElementsByTagName("textarea");
for (i = 0; i < txt.length; i++) {
if (txt[i].id.indexOf("TextBox1") != -1) {
if (txt[i].value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
}
function f1(sender, args) {
args.IsValid = false;
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
var txt = gridview.getElementsByTagName("textarea");
for (i = 0; i < txt.length; i++) {
if (txt[i].id.indexOf("TextBox2") != -1) {
if (txt[i].value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
}
I would like to call these function from my code behind and also I would like to assign the function to custom validator
I tried some thing as follows but not working
<asp:CustomValidator ID="custValCountry" runat="server" ValidationGroup="Country"
ValidateEmptyText="true" ControlToValidate="TextBox1" ClientValidationFunction="javascript:f"
ErrorMessage="Other is required"></asp:CustomValidator>
Also my under my RowDataBound event I write as follows this is also not working
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = (TextBox)e.Row.FindControl("TextBox1");
Page.ClientScript.RegisterClientScriptBlock(txt.GetType(), "onBlur", "multiplication('" + txt.ClientID + "')");
//Page.ClientScript.RegisterClientScriptBlock(, "Script", "alert('Records Successfuly Saved!');", true);
// txt.Attributes.Add("onBlur", "return javascript:multiplication('" + txt.ClientID + "');");
//TextBox txt1 = (TextBox)e.Row.FindControl("TextBox2");
txt1.Attributes.Add("onBlur", "return javascript:multiplication('" + txt1.ClientID + "');");
}
}
Can some one help me
Static JavaScript files do not get fed through ASP.NET normally, so this line will not work:
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
Use a fixed ID for the grid and specify it directly:
var gridview = document.getElementById('my-grid');
<asp:GridView ID="my-grid" ClientIDMode="Static" runat="server" ...>
Or come up with some other way of finding the ID.
Also note that this function is next to worthless:
function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}
You get the weight then do nothing with it?
You need to realize that your javascript functions are running in the client's browser, not on your server where your code behind is running. If you need to call the functions from your code behind, you will need to create equivalent functions in your code behind.
I have a bunch of different panels that are custom server controls, which inherits CompositeControl. The panels are rendered by using the CreateChildControls(). I have a page where I am displaying them based off of a users selection from a comboBox. When you change the selection it does a callback for a callback panel (DevExpress control), which is like an update panel. Based on the selection it adds the panel to the callback panel. But it seems that if you do this from a callback the server controls life cycle doesn't get started, so it never calls CreateChildControls() or OnPreRender(). Any ideas on how to make this work? EnsureChildControls() doesn't seem to helping.
Here is some example code of one of the panels
protected override void CreateChildControls()
{
base.CreateChildControls();
String strParentID = this.ClientInstanceName.Length > 0 ? this.ClientInstanceName : this.ClientID;
String strID = "";//Used as ID and ClientInstanceName.
String strKey = "";//Used in the ID and as the ControlInfo key.
if (!DesignMode)
{
//*******************************************************************
ASPxLabel lblUnit = new ASPxLabel();
lblUnit.Text = "Select Unit(s)";
callbackEdit.Controls.Add(lblUnit);
//*******************************************************************
strKey = "btnUnitSelector";
strID = strParentID + "_" + strKey;
btnUnitSelector = new ASPxButton()
{
ID = strID,
ClientInstanceName = strID,
CssFilePath = this.CssFilePath,
CssPostfix = this.CssPostfix,
SpriteCssFilePath = this.SpriteCssFilePath,
};
btnUnitSelector.Width = Unit.Pixel(180);
btnUnitSelector.AutoPostBack = false;
this.listControlInfo.Add(new ControlInfo(strKey, btnUnitSelector.ClientInstanceName, btnUnitSelector.ClientID));
callbackEdit.Controls.Add(btnUnitSelector);
//*******************************************************************
strKey = "unitPopup";
strID = strParentID + "_" + strKey;
unitPopup = new UnitPopup.UnitPopup();
unitPopup.ID = strID;
unitPopup.ClientInstanceName = strID;
unitPopup.btnOk_AutoPostBack = false;
unitPopup.ShowOnlyUnits = false;
unitPopup.DataSource = GlobalProperties.Company_UnitsAndAreas;
unitPopup.DataBind();
btnUnitSelector.ClientSideEvents.Click = "function (s, e) { " + unitPopup.ClientInstanceName + ".Show(); }";
unitPopup.ClientSideEvents.MemberSet = "function (s, e) { " + btnUnitSelector.ClientInstanceName + ".SetText(" + unitPopup.ClientInstanceName + ".selectedMemberName); }";
Controls.Add(unitPopup);
//*******************************************************************
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ClientScriptManager cs = this.Page.ClientScript;
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName = "QSR_ServerControls.Controls.DashboardControls.SalesChart.SalesChart.js";
cs.RegisterClientScriptResource(typeof(SalesChart), resourceName);
}
Here is some sample code of adding a panel
private void PopulatePanel(string panel)
{
tblDescCell.Controls.Add(new LiteralControl(GetPanels().Select("[PanelName] = '" + panel + "'")[0]["PanelDescription"].ToString()));
if (panel == "SalesChart")
tblTopLeftCell.Controls.Add(new SalesChart.SalesChart());
}
void callbackMain_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
PopulatePanel(e.Parameter);
}
During callback requests PreRender and Render methods are not executed (this is the main difference from PostBack request). But CreateChildControls should be executed. Please provide more information or code example.
my client side code button1.Attributes.Add("onclick", "javascript:window.open('page1.aspx?CheckedItem=" + checkedItem.ToString() + "','mywindow',');"); is not executing on the first click.But it is working fine from second click onwards.I wrote this code inside the button click event.
I had tried to put this inside the page_load ,but the problem is i need to return a value from this page.
here is the code
protected void btnPreview_Click(object sender, EventArgs e)
{
//StringBuilder checkedItem = new StringBuilder();
checkedItem.Length = 0;
foreach (ListItem i in chkValidation.Items)
{
if (i.Selected)
{
if (string.IsNullOrEmpty(Convert.ToString(checkedItem)))
{
checkedItem.AppendFormat(i.Text);
}
else
{
checkedItem.AppendFormat(",");
checkedItem.AppendFormat(i.Text);
}
}
btn_Preview.Attributes.Add("onclick",
"javascript:window.open('TimePhaseAttributePreview.aspx?CheckedItem=" +
checkedItem.ToString() + "','mywindow','menubar=0,resizable=0,width=350,height=250');");
}
Please help me
put the code in any page event. like page_load,init.. or use RegisterClientScriptBlock
You need to use OnClientClick, not OnCLick
Change your code to
button1.OnClientClick = "javascript:window.open('page1.aspx?CheckedItem=" + checkedItem.ToString() + "'
,'mywindow',')";