window.open on load page (ASP.NET) using Method=POST - asp.net

i need open pop up in asp.net using post Method and window.open to rezise te new windows.
my code:
Open the pop up:
function mdpbch(URL) {
child = window.open(URL, "passwd","dependent=1,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=600,height=475");
child.location.href = URL;
if (child.opener == null) {
child.opener = window;
}
child.opener.name = "opener";
}
URL:
function PagoEnLinea(Banco)
{
switch(x){
case "BCH":
document.frmEnvia.action = SERV + "/llamacom.asp";
url = SERV + "lamacom.asp
alert(url);
mdpbch(url);
document.frmEnvia.submit();
break;
}
}
ASPX:
<body>
<form id="frmEnvia" runat="server" name="formulario" method="post" target="_blank">
<div style="visibility:hidden;">
<asp:TextBox ID="txtXml" runat="server" Visible="true" />
</div>
.....
</body>
on page load (code behind) i create a xml string and put it in the textbox txtXml.
i need use post method becose the server validate te method, and window.open becose need customize the pop up
thanks

I think you should manipulate the object:
parentWindow
Inside the document object; before you submit the form, something like this:
switch(x){
case "BCH":
document.frmEnvia.action = SERV + "/llamacom.asp";
url = SERV + "lamacom.asp
alert(url);
mdpbch(url);
//here you manipulate the parentWindow element
document.parentWindow.scrollbars... (add the attributes you need)
//--
document.frmEnvia.submit();
break;
}

Since you are setting the name of the popup to passwd, you should then be able to set the target attribute of the form to passwd.
So the only change needed is the following:
<form ... target="passwd">

Related

Add Link Button in specific location

My current scenario is I retrieved the HTML of a page using the following method.
readStream = New StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet))
Dim fullString As String = readStream.ReadToEnd()
I did further formatting of the HTML before setting it to the innerHtml of my div.
displaystring = Regex.Replace(fullString, "<div.*?>", "<div>")
displaystring = Regex.Replace(fullString, "<span.*?>", "<span>")
displaystring = Regex.Replace(fullString, "<table.*?>", "<table>")
For example, I have a part of HTML code which is
<a>Brazil</a>
And I have tried fullstring = Regex.Replace(fullstring, "<a>Brzail</a>", <asp:Linkbutton name="lnkTest" runat="server"). And I realized it cannot work because ASP controls cannot be appended as string.
How can I control.Add just after <a>Brazil</a>? Any other suggestions are welcome too.
You cannot add ASP.Net Server control like this. You can use html control anchor tag or button and on click of this you can make an AJAX call.
Sample code will be like this
fullstring = Regex.Replace(fullstring, "<a>Brzail</a>", "<a href='#' onclick='clickMe'>Link</a>")
In Server side C# you can write a page method
like `
[PageMethod]
public static string MyMethod()
{
//Your logic
return "";
}
`
In javascript
function cickMe()
{
$.ajax({
url: "Sample.aspx/MyMethod",
success: function(data){
//your logic
}
});
}

Asp button to open new page without submit

I have this aspx script for the button for pop-up:
<asp:Button ID="btnNewEntry" Text="Post Code Search" OnClick="btnNewEntry_Click" runat="Server" target="_blank"/>
and behind:
protected void btnNewEntry_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.Page.GetType(), "", "window.open('../search/postcode_search/Default.aspx?code="+ p +"','Post Code Search','width=800,height=300,left=100,top=100,resizable=yes'); popup_handle.focus();", true);
}
But as the button is clicked the pop-up is opened but the parent page is refreshed. Why it's so? any work around?
Page got refreshed when a request to server is made, and server controls like Button has a property AutoPostback = true by default which means whenever they are clicked a trip to server will be made. Set AutoPostback = false for insert button, and this will do the trick for you.
or
Add OnClientClick="return false;" ,
<asp:button ID="btninsert" runat="server" text="Button" OnClientClick="return false;" />
Perhaps a little explanation of what is actually happening with your code will help. We have already discussed the auto postback, so you know that clicking that button will send the event back to the server. The page initializes again and reloads the view state and all of the posted data. After that, the button click event is handled.
At this point, your code writes the window.open script to the page. Keep in mind this is no where specific. This is just script that is added some where on the page and executed. The view state then gets updated and the page is sent back to the client. If the user reloads the page, that script is going to execute again.
Your best bet is going to be converting that to a client side button only. Find a way to get the necessary data back from the server before loading your popup. The easiest way to do that is make an AJAX call and open your pop up on success from your end point.
Try this.Updated one.
<asp:Button ID="btnNewEntry" Text="Post Code Search" OnClick="btnNewEntry_Click" runat="Server" target="_blank"
OnClientClick="javascript:window.open('../search/postcode_search/Default.aspx?code=+ p','Post Code Search','width=800,height=300,left=100,top=100,resizable=yes').focus();return false;"/>
Issue was due to "+ p +".
So as advised, i decided to go to client side. Here is my script:
<button onclick="OpenPopup()" type="button">Post Code Search</button>
and javascript code above it:
<script>
function OpenPopup() {
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
var str = getQueryString('code');
if (str != null) {
p = str.replace(/%20/g, ' ');
}
else {
p = "";
}
var url = "../search/postcode_search/Default.aspx?code=" + p;
window.open(url, "Post Code Search", "toolbar=no, location=no,status=yes,menubar=no,scrollbars=yes,resizable=no, width=750,height=400,left=430,top=100");
return false;
}
</script>
so basically what it does, it grabs parameter from parent window url and adds to popup window url. My parent window url:
/Customer.aspx?code=V6E%20111&firstname=MyName
I hope it helps for others as well. Thanks for help guys.

inside the usercontroler which is dynamically loaded,FileUploadField issue

my question is related to the fileupload control.I am loading my usercontrollers dynamically via ashx handler.so far so good.but when I put
<ext:FileUploadField runat="server" />
my ashx handler give me error which tell me null reference .
I am doing this with the text,textfield elements ,in that case, no problem ,my user control loading without no problems.
(<ext:TextField runat="server" FieldLabel="deneme"></ext:TextField>)
someone tell me where is the problem .
here is the my ashx handler,
public void ProcessRequest(HttpContext context)
{
string mainTabPnl = context.Request["container"];
string url = context.Request["url"];
string id = context.Request["id"];
Ext.Net.Panel pn = new Ext.Net.Panel()
{
Title = "MY TITLE",
Closable = true,
Layout = "Fit",
Height=500,
ID=id,
Items = {
new UserControlLoader{
Path=url
}
}
};
pn.AddTo(mainTabPnl);
new DirectResponse().Return();
}
ext:FileUploadField
should be placed inside html form tag
<form>
<ext:FileUploadField
</form>

Asp.Net Check file size before upload

I want to check the selected file size BEFORE uploading a file with the asp fileupload component.
I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..)
How can I do that ?
Thanks for your answers..
ASPX
<asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" />
<asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" />
<asp:Label ID="lbl_uploadMessage" runat="server" Text="" />
jQuery
function setUploadButtonState() {
var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024
var fileUpload = $('#fileUpload');
if (fileUpload.val() == '') {
return false;
}
else {
if (fileUpload[0].files[0].size < maxFileSize) {
$('#button_fileUpload').prop('disabled', false);
return true;
}else{
$('#lbl_uploadMessage').text('File too big !')
return false;
}
}
}
I am in the same boat and found a working solution IF your expected upload file is an image. In short I updated the ASP.NET FileUpload control to call a javascript function to display a thumbnail of the selected file, and then before calling the form submit then checking the image to check the file size. Enough talk, let's get to the code.
Javascript, include in page header
function ShowThumbnail() {
var aspFileUpload = document.getElementById("FileUpload1");
var errorLabel = document.getElementById("ErrorLabel");
var img = document.getElementById("imgUploadThumbnail");
var fileName = aspFileUpload.value;
var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
if (ext == "jpeg" || ext == "jpg" || ext == "png") {
img.src = fileName;
}
else {
img.src = "../Images/blank.gif";
errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
}
img.focus();
}
function CheckImageSize() {
var aspFileUpload = document.getElementById("FileUpload1");
var errorLabel = document.getElementById("ErrorLabel");
var img = document.getElementById("imgUploadThumbnail");
var fileName = aspFileUpload.value;
var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
if (!(ext == "jpeg" || ext == "jpg" || ext == "png")) {
errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
return false;
}
if (img.fileSize == -1) {
errorLabel.innerHTML = "Couldn't load image file size. Please try to save again.";
return false;
}
else if (img.fileSize <= 3145728) {
errorLabel.innerHTML = "";
return true;
}
else {
var fileSize = (img.fileSize / 1048576);
errorLabel.innerHTML = "File is too large, must select file under 3 Mb. File Size: " + fileSize.toFixed(1) + " Mb";
return false;
}
}
The CheckImageSize is looking for a file less than 3 Mb (3145728), update this to whatever value you need.
ASP HTML Code
<!-- Insert into existing ASP page -->
<div style="float: right; width: 100px; height: 100px;"><img id="imgUploadThumbnail" alt="Uploaded Thumbnail" src="../Images/blank.gif" style="width: 100px; height: 100px" /></div>
<asp:FileUpload ID="FileUpload1" runat="server" onchange="Javascript: ShowThumbnail();"/>
<br />
<asp:Label ID="ErrorLabel" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click" Width="70px" OnClientClick="Javascript: return CheckImageSize()" />
Note the browser does take a second to update the page with the thumbnail and if the user is able to click the Save before the image gets loaded it will get a -1 for the file size and display the error to click save again. If you don't want to display the image you can make the image control invisible and this should work. You will also need to get a copy of blank.gif so the page doesn't load with a broken image link.
Hope you find this quick and easy to drop in and helpful. I'm not sure if there is a similar HTML control that could be used for just general files.
Here I come to save the day! sorry i am 3 years late but, let me reassure everyone that this is quite possible and not to hard to implement! You simply need to output the filesize of the file being uploaded to a control that can be validated. You can do this with javascript, which will not require an ugly postback, where as if you were to use
FileBytes.Length
you will encounter a postback after the end user has selected an image. (I.E. using the onchange="file1_onchange(this);" to accomplish this.). Whichever way you choose to output the filesize is up to you the developer.
Once you have the filzesize then simply output it to a ASP control that can be validated. (I.E. a textbox) then you can use a regular expression for a range to validate for your filesize.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^([1-9][0-9]{0,5}|[12][0-9]{6}|3(0[0-9]{5}|1([0-3][0-9]{4}|4([0-4][0-9]{3}|5([0-6][0-9]{2}|7([01][0-9]|2[0-8]))))))$" ErrorMessage="File is too large, must select file under 3 Mb." ControlToValidate="Textbox1" runat="server"></asp:RegularExpressionValidator>
Boom! it's that easy. Just make sure to use the Visibility=Hidden on your ASP control to be validated and not Display=None because Display=none will appear on the page at all (although you can still interact with it through the dom). And Visibility=Hidden is not visible, but space is allocated for it on the page.
check out: http://utilitymill.com/utility/Regex_For_Range for all your regex range needs!
I think it is possible using javascript look here
I think you cannot do that.
Your question is similar to this one : Obtain filesize without using FileSystemObject in JavaScript
The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server.
So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
You can do that by using javascript.
Example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileSize() {
var input, file;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
}
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
</form>
</body>
</html>
To validate multiple files with jQuery + asp:CustomValidator a size up to 10MB
jQuery:
function upload(sender, args) {
args.IsValid = true;
var maxFileSize = 10 * 1024 * 1024; // 10MB
var CurrentSize = 0;
var fileUpload = $("[id$='fuUpload']");
for (var i = 0; i < fileUpload[0].files.length; i++) {
CurrentSize = CurrentSize + fileUpload[0].files[i].size;
}
args.IsValid = CurrentSize < maxFileSize;
}
ASP:
<asp:FileUpload runat="server" AllowMultiple="true" ID="fuUpload" />
<asp:LinkButton runat="server" Text="Upload" OnClick="btnUpload_Click"
CausesValidation="true" ValidationGroup="vgFileUpload"></asp:LinkButton>
<asp:CustomValidator ControlToValidate="fuUpload" ClientValidationFunction="upload"
runat="server" ErrorMessage="Error!" ValidationGroup="vgFileUpload"/>
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: http://blueimp.github.io/jQuery-File-Upload/
It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx
$(document).ready(function () {
"use strict";
//This is the CssClass of the FileUpload control
var fileUploadClass = ".attachmentFileUploader",
//this is the CssClass of my save button
saveButtonClass = ".saveButton",
//this is the CssClass of the label which displays a error if any
isTheFileSizeTooBigClass = ".isTheFileSizeTooBig";
/**
* #desc This function checks to see what size of file the user is attempting to upload.
* It will also display a error and disable/enable the "submit/save" button.
*/
function checkFileSizeBeforeServerAttemptToUpload() {
//my max file size, more exact than 10240000
var maxFileSize = 10485760 // 10MB -> 10000 * 1024
//If the file upload does not exist, lets get outta this function
if ($(fileUploadClass).val() === "") {
//break out of this function because no FileUpload control was found
return false;
}
else {
if ($(fileUploadClass)[0].files[0].size <= maxFileSize) {
//no errors, hide the label that holds the error
$(isTheFileSizeTooBigClass).hide();
//remove the disabled attribute and show the save button
$(saveButtonClass).removeAttr("disabled");
$(saveButtonClass).attr("enabled", "enabled");
} else {
//this sets the error message to a label on the page
$(isTheFileSizeTooBigClass).text("Please upload a file less than 10MB.");
//file size error, show the label that holds the error
$(isTheFileSizeTooBigClass).show();
//remove the enabled attribute and disable the save button
$(saveButtonClass).removeAttr("enabled");
$(saveButtonClass).attr("disabled", "disabled");
}
}
}
//When the file upload control changes, lets execute the function that checks the file size.
$(fileUploadClass).change(function () {
//call our function
checkFileSizeBeforeServerAttemptToUpload();
});
});
dont forget you probably need to change the web.config to limit uploads of certain sizes as well since the default is 4MB
https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx
<httpRuntime targetFramework="4.5" maxRequestLength="11264" />
Why not to use RegularExpressionValidator for file type validation.
Regular expression for File type validation is:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"

Telerik RadWindow Javascript return values to ASP.NET

I have a parent page that launches a telerik radwindow and passes it an argument.
Once the radwindow is done processeing the value, I need it to return it to the parent page, and I would like the parent page to have access to this value in my code behind page.
I have tried to pass the value to a hidden field on my page and then trigger a page refresh and my code behind watches to see if the value is working.
I can't seem to get this to work. I get the return value in the parent javascript, but i can't get it from my hidden field from the code behind.
I even get it into the text box like i need to but, when i find the Hidden field in the codebehind, there is no value set.
Where I have set alerts, I am getting the values displayed as i need to.
I suspect that the reason I can't see my return value in the code behind file, is that when the page is refreshed, I am getting a new page and not only causing a post back.
And is there not a better way i can do this.
here is my code in the parent page:
Parent ASPX:
<script type="text/javascript">
function OpenWnd() {
var oWnd = radopen(null, "RadWindow1");
}
function OnClientShow(oWnd) {
//Create a new Object to be used as an argument to the radWindow
var arg = new Object();
//Using an Object as a argument is convenient as it allows setting many properties.
arg.text = document.getElementById("TextBox1").value;
//Set the argument object to the radWindow
oWnd.Argument = arg;
}
function ClientCallBackFunction(radWindow, returnValue) {
//check if a value is returned from the dialog
if (returnValue.newtext) {
document.getElementById("Hidden1").value = returnValue.newtext;
alert("HiddenValue: " + document.getElementById("Hidden1").value);
}
}
</script>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<div>
<telerik:RadWindowManager ID="RadWindowManager2" runat="server">
<Windows>
<telerik:RadWindow ID="RadWindow1" runat="server" OnClientShow="OnClientShow" ClientCallBackFunction="ClientCallBackFunction"
NavigateUrl="Dialog2.aspx" />
</Windows>
</telerik:RadWindowManager>
</div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
<input type="button" value="Send content to dialog page" onclick="OpenWnd()" />
<p>
<input id="Hidden1" type="hidden" runat="server" />
</p>
</form>
Parent Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
HtmlInputHidden hidden = (HtmlInputHidden)Page.FindControl("Hidden1");
if (IsPostBack && !string.IsNullOrEmpty(hidden.Value))
{
//Code Here
}
}
Here is my Dialog code:
Dialog ASPX:
<script type="text/javascript">
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function ConfigureDialog() {
//Get a reference to the radWindow wrapper
var oWindow = GetRadWindow();
//Obtain the argument
var oArg = oWindow.Argument;
//Use the argument
var oArea = document.getElementById("TextBox1");
oArea.value = oArg.text;
}
function SendAndClose() {
var oWindow = GetRadWindow();
//Get current content of text area
var arg = new Object();
arg.newtext = document.getElementById("TextBox1").value;
oWindow.Close(arg);
RefreshParentPage();
}
function RefreshParentPage() {
GetRadWindow().BrowserWindow.location.reload();
alert("RefreshParentPage");
}
</script>
Thanks for all the help
Ian
You are doing the following
GetRadWindow().BrowserWindow.location.reload();
But that wont cause a postback it will simply reload the parent page, you need to cause a potback.
You could try adding a button to the parent form with the style set 'display:none', and handling the click event in the code behind, you can fire this button off from your js code.
In Parent Page :
<asp:Button runat="server" id="btnClick" Style="display:none" OnClick="btnClick_Click"/>
protected void btnClick_Click(object sender,EventArgs e)
{
string val = this.Hidden1.Value; //Code goes here
}
You can invoke from your javascript like this (non jQuery), place this in your callback
document.getElementById('<%= btnClick.ClientID').click();
A better approach would be this on the aspx side:
<%=this.ClientScript.GetPostBackEventReference(new System.Web.UI.PostBackOptions(btnClick))%>

Resources