I want to hide file upload control behind label I found solution for that on this link:
Styling an input type="file" button
There was a link to this example: http://jsfiddle.net/4cwpLvae/
Now by clicking on label it open file uploader and after uploading file it hides file upload tab, but I want to save file uploaded by that uploader in database throuh a function in aspx.cs file. How may I call that function?
This link did't help for me
How to call code behind function from label.text in asp.net
using file uploader in label is just for styling.
Here is my function that I want to call
protected void Button1_Click(object sender, EventArgs e)
{
if (!inputfile.HasFile)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
//Response.Write("No file Selected"); return;
}
else
{
string filename = Path.GetFileName(inputfile.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = inputfile.PostedFile.ContentType;
HttpPostedFile file = inputfile.PostedFile;
byte[] document = new byte[file.ContentLength];
file.InputStream.Read(document, 0, file.ContentLength);
/* Stream fs = inputfile.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);*/
if ((extension == ".pdf") || (extension == ".doc") || (extension == ".docx") || (extension == ".xls")
|| (extension == ".pptx"))//extension
{
if (file.ContentLength <= 31457280)//size
{
FYPEntities2 obj = new FYPEntities2();
tblFile us = new tblFile();
us.Name = filename;
us.ContentType = contentType;
us.Data = document;
// us.Data = bytes;
us.Date = DateTime.Now;
obj.tblFiles.Add(us);
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Hello World');", true);
obj.SaveChanges();
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "filesize();", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "invalidformat();", true);
}
}
}
I think you are looking for this. Put a LinkButton on the page and give it no Text, so it is not visible for the user but does still exists.
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
</style>
<label for="<%=FileUpload1.ClientID %>" class="custom-file-upload">
<i class="fa fa-cloud-upload">Custom Upload</i>
</label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="Button1_Click"></asp:LinkButton>
Then in code behind attach an onchange attribute to FileUpload1 with the UniqueID of LinkButton1. When the upload changes, javascript will file the PostBack event of the LinkButton thus automatically uploading the file.
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
}
Related
I have a requirement to read image data from SQL Server (company logo) and keep it in localStorage. This company logo is displayed in the master page left sidebar so that in every client page it will be visible.
I use 3 JS functions in the Master page for this purpose.
function storageCheck() {
if (localStorage.getItem("imgData") === null) //check availability
document.getElementById('<%=hdfStorage.ClientID %>').value = "true"; //assign true to a hidden field
else
document.getElementById('<%=hdfStorage.ClientID %>').value = "false";
}
function storelogo(imgData) { //store image data
localStorage.setItem("imgData", imgData);
}
function getImg() { //get data
var dataImage = localStorage.getItem('imgData');
document.getElementById('imgCompanyLogo').src = dataImage;
alert('got')
}
In the code behind of the Master page I am calling these JS functions
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!IsPostBack)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "checkfn", "storageCheck()", true);
if (hdfStorage.Value == "true")
ScriptManager.RegisterStartupScript(this, this.GetType(), "storelogoo", "storelogo('" + <Base64String img data from database> + "');", true);
else if (hdfStorage.Value == "false")
ScriptManager.RegisterStartupScript(this, this.GetType(), "getlogo", "getImg();", true);
}
}
I have tried putting it in the Page_Load event but no use. The issue I am facing is these functions are not getting called and if called from the Page Load event the hiddenfield control wont get the value when I check using hdfStorage.Value == "true"
I suggest to put it in memory as singleton or session, all people work like this
I have an ASP.NET Web forms site with C# code behind called from VS2013 running under Win 10 and viewed in Google Chrome. I am trying to call a C# function from Javascript in the Default.aspx markup as shown below
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
<img id="imgPaste" src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
<asp:Button Text="Save" runat="server" OnClick="Save" />
<input id="Text1" type="text" name ="ImageData" hidden="hidden" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('txtPaste').focus();
document.getElementById('txtPaste').onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items));
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
document.getElementById("imgPaste").src = event.target.result;
document.getElementById("Text1").value = event.target.result;
PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
};
reader.readAsDataURL(blob);
}
}
};
function onSuccess(result) {
alert("Success! " + result);
}
function onFailure(result) {
alert("Failed! " + result);
}
</script>
</asp:Content>
The PageMethod is defined in Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Save(object sender, EventArgs e)
{
string str = Request.Form["ImageData"];
SaveImg(str);
}
[WebMethod]
public static bool SaveImg(string str)
{
try
{
string imageData = str.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(imageData);
string filePath = #"C:\Windows\Temp\File.jpg";
if (File.Exists(filePath)) File.Delete(filePath);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
return false;
}
catch (Exception Ex)
{
return true;
}
}
}
When I click in txtPaste and paste an image, the image appears in imgPaste OK and can be downloaded as a file by clicking by the Save button to execute the SaveImg function.
I am trying to create the file only by pasting an image, without clicking the Save button by defining SaveImg as Web Method and calling PageMethods.SaveImg after filling the Image control. The call to SaveImg shows and alert as specified in the OnSuccess function, but SaveImg is not executed - breakpoints set in the function are not hit on the Paste event, although they are if the Save button is clicked. The same behaviour is shown if the web site is viewed in Firefox.
ScriptManager in the Master.aspx file has EnablePageMethods set to True.
I have tried the following to make SaveImg execute on the paste event without success:
1) Commenting out settings.AutoredirectMode in Route.Config made PageMethods.SaveImg return a Fail status.
2) Commenting one or both lines in global.asax:
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
3) Using an AJAX function as shown below. sParam was defined as event.target.result.toString() and the call replaced the PageMethods.SaveImg call
function showDetail(sParam) {
$.ajax({
type: "POST",
url: "Default.aspx/SaveImg",
data: "{'str': '" +sParam +"'}", // passing the parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(retValue) {
// Do something with the return value from.Net method
}
});
Calling a C# function from Javascript in ASP.Net can be done by placing the C# function in the click event of a control and then calling the control's click event from Javascript as shown below for the above scenario:
JavaScript in page markup:
%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="txtPaste" name="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
<img id="imgPaste" src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
<asp:Button Text="Save" runat="server" OnClick="cmdSave_Click" ID="cmdSave" />
<input id="Text1" type="hidden" name ="ImageData" hidden="hidden" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('txtPaste').focus();
document.getElementById('txtPaste').onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items));
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
document.getElementById("imgPaste").src = event.target.result;
document.getElementById("Text1").value = event.target.result;
//PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
document.getElementById("txtPaste").value = "Image Pasted"
document.getElementById("cmdSave").click();
};
reader.readAsDataURL(blob);
}
}
};
</script>
C# code:
protected void cmdSave_Click(object sender, EventArgs e)
{
string str = Request.Form["ImageData"];
SaveImg(str);
}
public bool SaveImg(string str)
{
try
{
string imageData = str.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(imageData);
string filePath = #"C:\Windows\Temp\File.jpg";
if (File.Exists(filePath)) File.Delete(filePath);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
return false;
}
catch (Exception Ex)
{
return true;
}
}
I have a submit button and below is the code in the onClick event :
protected void btnSubmit_Click(object sender, EventArgs e)
{
...
ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Submitted')", true);
}
This code works.
But the problem is when user go to next page by this:
Response.Redirect("page2.aspx");
and when click backspace to get back to page1 and,
before the reload,
the following message box appears!!
this problem happened again when we refresh(F5) the page1 after submiting
how will I solve this?
I tried:
1. if(isPostback)// before the alert
2. string message = "Submitted";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
In such case, you can implement a special code block to detect browser refresh as
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}
In the button submit you can do it as
protected void btn3_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here
}
}
I have a fileupload control and a button in a webform.When i click on the button after selecting fileupload,it should save the image and rename it with a GUID.
protected void btnUpload_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filePath = string.Empty;
string extension = string.Empty;
try
{
//Check if Fileupload control has file in it
if (FileUpload1.HasFile)
{
// Get selected image extension
extension = Path.GetExtension(FileUpload1.FileName).ToLower();
//Check image is of valid type or not
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
{
//Cretae unique name for the file
fileName = Guid.NewGuid().ToString() + extension;
//Create path for the image to store
HiddenField1.Value = fileName;
filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
//Save image in folder
FileUpload1.SaveAs(filePath);
//Show the panel and load the uploaded image in image control.
//pnlCrop.Visible = true;
}
The above code works just fine,saves the image and passes the GUID to the hiddenfield.Now i want to pass the value of hiddenfield to a client side variable and then display it as an alert.
<script type="text/javascript">
function showfilename() {
setTimeout(function () {
var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
alert(dpGUID);
},3000)
}
</script>
Reason for using timeout? Because i want to read value of hiddenfield after it has been assigned the value on button click.
Note:I am using two functions on Buttonclick.One on client side and other on server side as follows :
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />
Is it possible? If yes,what could be causing a problem?
Try using a RegisterClientScriptBlock
protected void btnUpload_Click(object sender, EventArgs e)
{
/*All your code here*/
//instead of HiddenField1.Value = fileName; write the line below
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
}
and now you can get rid of the OnClientClick="showfilename() and the HiddenField
I tried to implement Jquery.Spell.Checker in asp.net application but it gives error as shown in following image.
Anyone suggest me how to resolve it.
CLICK HERE TO SEE THE SAMPLE
PS:
I have done changes in my application but still doesn't working and display alert message as per above image.Please let me know if i was missing something.The code given below:
LINK:
<link href="JQuerySpellChecker/spellchecker.css" rel="stylesheet" type="text/css" />
<script src="JavaScript/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="JQuerySpellChecker/jquery.spellchecker.js" type="text/javascript"></script>
CSS:
<style type="text/css">
body {
margin: 1em;
font-family: 'lucida grande',helvetica,verdana,arial,sans-serif;
}
#textarea-example {
width: 562px;
}
textarea {
font-size: 90%;
margin-bottom:10px;
padding: 5px;
border: 1px solid #999999;
border-color: #888888 #CCCCCC #CCCCCC #888888;
border-style: solid;
height: 20em;
width: 550px;
}
button {
font-size: 90%;
cursor: pointer;
}
.loading {
padding: 0.5em 8px;
display: none;
font-size: small;
}
</style>
HTML:
<div id="textarea-example">
<p>
<label for="text-content">Add your own text and check the spelling.</label>
</p>
<textarea id="text-content" rows="5" cols="25"></textarea>
<div>
<button id="check-textarea">Check Spelling</button>
<span class="loading">loading..</span>
</div>
</div>
JAVASCRIPT:
// check the spelling on a textarea
$("#check-textarea").click(function(e){
e.preventDefault();
$(".loading").show();
$("#text-content")
.spellchecker({
url: "CheckSpelling.aspx", // default spellcheck url
lang: "en", // default language
engine: "google", // pspell or google
addToDictionary: false, // display option to add word to dictionary (pspell only)
wordlist: {
action: "after", // which jquery dom insert action
element: $("#text-content") // which object to apply above method
},
suggestBoxPosition: "below", // position of suggest box; above or below the highlighted word
innerDocument: false // if you want the badwords highlighted in the html then set to true
})
.spellchecker("check", function(result){
// spell checker has finished checking words
$(".loading").hide();
// if result is true then there are no badly spelt words
if (result) {
alert('There are no incorrectly spelt words.');
}
});
});
// you can ignore this; if document is viewed via subversion in google code then re-direct to demo page
if (/jquery-spellchecker\.googlecode\.com/.test(window.location.hostname) && /svn/.test(window.location)) {
window.location = 'http://spellchecker.jquery.badsyntax.co.uk/';
}
CheckSpelling.aspx
protected void Page_Load(object sender, EventArgs e)
{
string str = Request["str"];
//string str = "goood";
if (str != null)
{
string url = "https://www.google.com";
string path = "/tbproxy/spell?lang=en&hl=en";
// setup XML request
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
xml += "<spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\">";
xml += "<text>" + str + "</text></spellrequest>";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(xml);
WebProxy objWP = new WebProxy("address", 1978);
objWP.Credentials = new NetworkCredential("mysystemname", "password");
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + path);
request.Proxy = objWP;
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = data.Length;
System.IO.Stream stream = request.GetRequestStream();
// Send the data.
stream.Write(data, 0, data.Length);
stream.Close();
// Get the response.
System.Net.WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
stream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
stream.Close();
response.Close();
Response.ContentType = "text/xml";
MatchCollection result = Regex.Matches(responseFromServer, "<c o=\"([^\"]*)\" l=\"([^\"]*)\" s=\"([^\"]*)\">([^<]*)</c>");
if (result != null && result.Count > 0)
Response.Write(result[0].Value);
}
Response.Write("Failed");
}
You need to write yourself an ASP version of the included PHP server side file. Essentially, the server side component proxies a request off to Google or uses a PHP spell checker. Since you wouldn't really want to convert the whole of the Pspell library, I would recommend simply wrapping up the call to Google's spell check site.
i.e. Create an ASPX page and add the following code to it
<%# Import Namespace="System.Xml" %>
<script language="C#" runat="server">
public void Page_Load(Object src, EventArgs e)
{
var str = Request["str"];
if (str != null)
{
var url = "https://www.google.com";
var path = "/tbproxy/spell?lang=en&hl=en";
// setup XML request
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
xml += "<spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\">";
xml += "<text>" + str + "</text></spellrequest>";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(xml);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + path);
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = data.Length;
System.IO.Stream stream = request.GetRequestStream();
// Send the data.
stream.Write(data, 0, data.Length);
stream.Close();
// Get the response.
System.Net.WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
stream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
stream.Close();
response.Close();
Response.ContentType = "text/xml";
MatchCollection result = Regex.Matches(responseFromServer, "<c o=\"([^\"]*)\" l=\"([^\"]*)\" s=\"([^\"]*)\">([^<]*)</c>");
if (result != null && result.Count > 0)
Response.Write(result[0].Value);
}
Response.Write("Failed");
}
</script>
Then change the call in the js to call your new aspx file rather than the 'checkspelling.php'
Might be a bit late for you, but for any one else trying to resolve this problem, Jack Yang has produced an ASP implementation of checkspelling.php it can be found at
https://github.com/jackmyang/jQuery-Spell-Checker-for-ASP.NET
The plugin only does the client-side code. You'll have to supply it with your ASP script's URL.
Read the documentation.