I have for example 5 fileupload controls and Also I have a submit button for each of them (in front of each fileupload control) which will upload that fileupload's selected file(s).
But There is a problem, when I click on (for example) second submit button to upload second fileupload's file(s), we will have a post back and other fileupload's file(s) will reset to empty. How can I manage such situation so when the user click on a submit button, the related fileupload's file(s) upload and the other fileupload's file(s) stay in their states. Hope I'm clear enough.
A Picture for better Result:
Disclaimer - this is just modification of great answer here: How can I upload files asynchronously?
And I'm assuming you have jQuery.
<div>
<asp:FileUpload ID="fu1" runat="server" CssClass="fu1" />
<asp:Button ID="btn1" runat="server" OnClientClick="upload(this,'.fu1'); return false" Text="Submit" />
</div>
<div>
<asp:FileUpload ID="fu2" runat="server" CssClass="fu2" />
<asp:Button ID="btn2" runat="server" OnClientClick="upload(this,'.fu2'); return false" Text="Submit" />
</div>
<script type="text/javascript">
function upload(element,selector)
{
var formData = new FormData();
formData.append('image', $(selector)[0].files[0]);
$.ajax({
url: '<%= Page.Form.Action %>', //Server script to process data
type: 'POST',
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
}
</script>
Then within Page_Load:
Page.Form.Attributes["enctype"] = "multipart/form-data";
var file = Request.Files["image"];
if (file != null)
{
// do something with the file
}
Related
I have jquery code on cc.js that I need to execute when an asp.net button is clicked.
The code on cc.js has a variable called settings and then submits these settings to an API (POST action) with the following code:
'Transaction Submit'
$.ajax(settings).done(function (response) {
console.log(response);
});
Basically I need this button <asp:Button ID="BtnSubmit" runat="server" Text="Submit" /> to execute that jquery code. How can I do so?
You are looking for the OnClientClick property
<asp:Button ID="BtnSubmit" runat="server" OnClientClick="JSFunctionName(); return false;" Text="Submit" />
You will need to add the additional return false statement to prevent a post back from occurring if you button element is located inside a form.
This is assuming you want to decouple your front end html from your js code by using an inline call. If that is not the case then you mod your cc.js to autobind on the element as others have mentioned. One thing they left out is that in that process is that IF you button is inside a form then you need to prevent the auto-post back like so:
$(document).ready(function() {
$("#BtnSubmit").click(function(){
JSFunctionName();
e.preventDefault();
});
});
If the ID of the button is BtnSubmit, then you should be able to add a event handler like this.
$(document).ready(function() {
$("#BtnSubmit").click(function(){
alert("button clicked - do stuff here.");
});
});
change the alert("button clicked - do stuff here."); to your ajax request code.
You can write the following code to create an event on Button click to call the jquery method..
Basically, you take the ID by $("#btnSubmit") and on its click event write your Ajax function.
$("#BtnSubmit).on('click',function() {
// your ajax code here
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />
Hope this helps.
Just Add a click event with your button id using jquery..
$("#BtnSubmit").on('click',function(){
console.log('success...');
//ajax call here...
});
You can use Ajax within JS functions. I'm not sure what version of .NET you're using, but I'll answer with what I know for MVC 5.
Here's how I would do it:
HTML
<button id="SubmitBtn">Submit</button>
JS(JQuery)
$('#SubmitBtn').on('click', function () {
//Transaction Submit
$.ajax({
type: "POST",
url: '/ProjectName/Controller/Method',
data: { methodParameter1: data1, methodParameter2: data2 },
success: function (data) {
//do whatever
}
error: function (response) {
//do whatever
}
});
});
I want the click event of a LinkButton in my GridView to not call the grid view's OnRowCommand event.
The reason is because I want to encapsulate this in an UpdatePanel and update ErrorUpdateTextBox without performing a postback.
<asp:GridView ID="DataSourceMappingGridView" runat="server" DataKeyNames="Index" ClientIDMode="Static" OnRowCommand="DataSourceMappingGridView_RowCommand" OnRowDataBound="DataSourceMappingGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="ErrorUpdatePanel" runat="server">
<ContentTemplate>
<asp:LinkButton ID="ErrorTextLinkButton" runat="server" Text='View Errors' OnClick="ErrorTextLinkButton_Click" />
<asp:TextBox ID="ErrorUpdateTextBox" runat="server" Text="">
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If you really want to avoid a post back (UpdatePanels still do a partial post back), then I would recommend capturing the link button's click event client-side and then doing an AJAX call to the server to save/get whatever data is relevant to the link button being clicked, like this:
Remove the OnClick attribute (leave the runat="server" attribute so you can add the ID value to the link button during binding) and add a class attribute to the LinkButton markup to allow jQuery to easily wire up a click event handler, like this:
<asp:LinkButton ID="ErrorTextLinkButton" runat="server" Text='View Errors'
class="error" />
$(document).ready(function() {
$('.error').click(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetError",
data: "{'id':'7'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// Do something error data returned here
}
});
});
});
Finally, create an ASP.NET AJAX Page Method, like this:
[WebMethod]
public static string GetError(int id)
{
// Go and get error data from database or service, etc.
return "Your error message here";
}
I have a page which displays the following content when it is loaded:
<div>
<img src="loading.gif" alt="Loading" /> Generating PDF Document, please wait.
<div>
At the same time, I want to run this method the code behind automatically:
private void GeneratePdf()
{
...
}
Lastly, I want to redirect the user to the File.pdf path once the GeneratePdf() method is completed.
How do I do this?
You need to use the Page_Load event as explained here. Additionally, this is a great explanation of the page life cycle. You should take a look at it. Here is some sample code from the above link:
<script runat="server">//This script runs on the server and dishes up some output for the page.
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>//This generates the textbox that will be given a value from the above script.
</form>
</body>
</html>
Hope this helps you!
I suggest to use GeneratePDF with ajax, so you can use like
$.ajax({
url: '/pdf/fiele_to_generate_pdf.aspx',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}});
so for loading you can use jquery, there is a good plugin named BlockUI you can use it before your ajax call.
You can use the asp:Timer control to indicate when your code-behind should be called
<asp:Timer runat="server" ID="timer1" Interval="3000" OnTick="timer1_Tick"></asp:Timer>
Then implement the Timer's Tick event. This will be called after 3 seconds (3000ms) as specified in the markup
protected void timer1_Tick(object sender, EventArgs e)
{
GeneratePdf();
Response.Redirect("~/somepath/generatedPDF.pdf");
}
Hello how i can load web forms inside one web forms div/
SO i have web form 'account' which opening inside master page.
on my account web form i have menu i want when user clicks it to load another web form inside account page.
I am using ASP.NET C#.
Sorry For My Bad English.
Thanks
If you want to do this server-side this can be accomplished by loading an instance of a usercontrol into your form vs. the actual page. Click here to see an MSDN example and be sure to use update panels to manage the post backs.
If you want to do this client side you can do so via ajax and calling an ashx (handler file)
To manage this client side:
within your aspx file add the following:
within the header
<script type="text/javascript">
$(function () {
$("#panel").hide();
});
$(document).ready(function () {
$(".slide").click(function () {
$("#panel").show("slow", false);
jQuery.ajax({
type: "POST",
url: "controlloader.ashx",
dataType: "html",
success: function (response) {
jQuery('#loadcontrol1').append(response);
},
error: function () {
jQuery('#loadcontrol1').append('error');
}
});
});
});
</script>
And then within the body
<body>
<form id="form1" runat="server" >
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<div id="panel" >
<p>stuff here</p>
</div>
<p><%= DateTime.Now %></p>
<div id="div1" class="slide">
<p class="btn-slide">Expand Panel</p>
</div>
<br />
<asp:Button Text="Click me" ID="clickButton" runat="server" />
<div id="loadcontrol1" />
</div>
</form>
</body>
Then within your ashx file
public class controlloader : IHttpHandler
{
//If annonymous id is turned on IRequireSessionState Interface may be needed to write session variabled such as user auth.
// Generic handlers by default implementIReadOnlySessionState
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(RenderPartialToString("~/Control1.ascx")); ;
}
private string RenderPartialToString(string controlname)
{
Page page = new Page();
Control control = page.LoadControl(controlname);
page.Controls.Add(control);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
You will also need to create the user control file but I'll leave that code to you.
There are a few things happening in this example. The button is used to proveout post-backs to ensure the control is not reloaded. I also added an animation which you don't need but this was an old proof-of-concept piece I had from a while back so you can ignore that chuck of code.
I know you mentioned the user of master pages so you will more than likely want to factor out the javascript into a js file and then be sure to load it using script manager as:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.7.js" />
<asp:ScriptReference Path="~/js/yourcontrolloader.cs" />
</scripts>
</asp:ScriptManager>
This is required when using master pages otherwise due to the server side rendering your references will be lost and the scripts never called. You could also use a partial reference in the actual page vs the masterpage but this is up to you.
Best of luck
Kindly help me with a solution to upload a image and display it client side. Simultaneously, I need to save the image in server without refreshing the entire page since, other controls are created dynamically using java script which will disappear when the entire page gets refreshed.
Solution Found:
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5">
<ItemTemplate>
<div id="divImage" runat="server" onclick="Test()" class="draggable">
<asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/MyImages/{0}") %>' runat="server" />
</div>
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/MyImages/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("MyImages"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();
}
You will need to use Ajax for this.
the most trivial solution maybe is using an iframe, containing the form, inside the page . When submitting the form only the iframe will be refreshed and not the whole page
otherwise you could send the base64 representation of your image to your server via ajax. This can be achieved in newer browser, loading the image in a <canvas> element and using toDataURL() method (see Get image data in JavaScript?)
Check out http://www.phpletter.com/Our-Projects/AjaxFileUpload/
You can use ajax to send image(s) you want,
first get the image data :
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
and send it to the server via ajax:
$.ajax({
type: 'POST',
url: 'Save_Picture.aspx/UploadPic',
data: '{ "imageData" : "' + Pic + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("Done, Picture Uploaded.");
}
});
and write a service on the server "Save_Picture.aspx/UploadPic" to read the image data:
byte[] data = Convert.FromBase64String(imageData);