I am trying to implement a feature where user uploads a file, server processes the file and and displays realtime notification to the client about the status of processing e.g. validated, imported etc. There are examples where the client sends data from textboxes to the javascript proxy.
$("#btnTest").click(function () {
myHub.testMethodOnHub($("#txtEmail").val());
});
I need to send binary data to the server via signalR so that server can process that data and notify client using SignalR.
EDIT :- I was able to call a JS method from aspx.cs to set the status client side - realtime. However, the message disappears after page finishes loading.
What I have tried :-
ASPX :-
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="MultipleStepsUsingSignalR._Default" %>
<script src="Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>
<body>
<form id="Form1" runat="server">
<p>
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="btnProcessFile" runat="server" Text="Process File"
onclick="btnProcessFile_Click" />
<asp:HiddenField ID="hdnConnectionId" runat="server"/>
<%--<asp:Label Text="" ID="lblStatus" runat="server" />--%>
<span id="lblStatus"></span>
</p>
</form>
<script type="text/javascript">
$(document).ready(function () {
var multipleStepsHub = $.connection.multipleStepsHub;
multipleStepsHub.MethodInJavascript = function (status) {
$('#lblStatus').append(status);
};
$.connection.hub.start().done(function () {
$('#<%= hdnConnectionId.ClientID %>').val($.connection.hub.id);
alert($('#lblStatus').text());
});
});
</script>
</body>
Hub
[HubName("multipleStepsHub")]
public class MultipleStepsHub : Hub
{
public void ExecuteMultipleSteps(string status)
{
}
}
Code-behind for aspx
protected void btnProcessFile_Click(object sender, EventArgs e)
{
string connectionId = hdnConnectionId.Value;
var context = GlobalHost.ConnectionManager.GetHubContext<MultipleStepsHub>();
byte[] dataFromPostedFile = GetDataFromUploadedFile(fileUpload.PostedFile.InputStream);
context.Clients[connectionId].MethodInJavascript("<br>File updloaded.");
Thread.Sleep(5000);
context.Clients[connectionId].MethodInJavascript("<br>Processing step1");
Thread.Sleep(5000);
context.Clients[connectionId].MethodInJavascript("<br>Processing step2");
Thread.Sleep(5000);
context.Clients[connectionId].MethodInJavascript("<br>Processing step3");
}
What do I expect :-
Status text changing to "Processing step1" then "Processing step2" and then "Processing step3"
What is the result :-
a) There is a change in the status periodically (after Thread.Sleep), however, when the page finishes, the status disappears. As you notice in the below, "Processing step1" and "Processing step2" do appear, but later disappear.
You have a mistake in your JavaScript method:
multipleStepsHub.MethodInJavascript = function (status) {
("#lblStatus").val(status);
};
should be
multipleStepsHub.MethodInJavascript = function (status) {
$('#<%= lblStatus.ClientID %>').text(status);
};
Note that ASP.NET auto-generates HTML element identifiers.
EDIT: If you don't want the page to reload after the upload finishes, well, you need to upload the files asynchronously. In HTML5, it's pretty easy to achieve. For another example of how to do it, see this question.
You can't send a regular file to a hub method. You can use a regular http handler or mvc or any other framework to post a file and use signalr to show updates.
protected void btnProcessFile_Click is a full postback to the server which means you are reloading the page and at this time SignalR is not yet (re)loaded. Try using Ajax requests after the page load has finished.
Related
I want to know all possible ways to trigger a button in jQuery, I tried this but it's not working,
$("#<%=btA.ClientID%>").trigger('click');
Note: its a ASP.Net button and what I want is to trigger button click so that it will trigger a code-behind click method of buttonA.
Try this
$("#<%=btA.ClientID%>").click();
if it doesn't work try to alert this and check if it is getting accessed by JQ
alert($("#<%=btA.ClientID%>").length);
Have you registered the event with jquery in following manner
$(function(){
$("#<%=btA.ClientID%>").click(function(){
// your logic here
});
});
One more thing to confirm, are you loading this button directly on page load or you are having some page update panel which load it afterwords?
If yes then you should bind the event to button in following manner
$(document).on('click',"#<%=btA.ClientID%>", function() {...});
$("#<%=btA.ClientID%>").click();
Or
$("input[id$='yourbuttonId'").click();
Reason that trigger not working is Jquery only allow you to trigger a click that Jquery has created. Use the trigger route after you have written a click listener.
Its beats me since it should be a very straightforward thing. I actually just tried it out and it worked without a hitch. Here is my markup:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btA.ClientID%>").trigger('click');
});
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lbA" runat="server"></asp:Label>
<asp:Button ID="btA" runat="server" OnClick="btA_Click" Text="Click Me!" />
</div>
</form>
</body>
</html>
... and I have this method in my code behind:
protected void btA_Click(object sender, EventArgs e)
{
lbA.Text = "Hello World!";
}
When the application runs, it triggers the click event of the btA button fires immediately and the Hello World! text is rendered on the label. Check if you could be missing something.
$("#<%=btA.ClientID%>").click();
I believe this is the only other way.
May be you are trying to wire the event,when the control itself is not loaded on to the page.
Try this instead.It buys a little bit of time and then wires up the event.
setTimeout(function () {
$("#<%=btA.ClientID%>").trigger('click');
}, 10);
I always make ClientIdMode="static" so that you can easily call the element with the same id you configured in the page..
So you dont hvae to use ClientID.. More over you cant use asp.net code in a separate js file.
$("#<%=btA.ClientID%>").trigger('click');
to
$("#btA").click();
Asp button is not working in a jquery dialog box:
<script type="txt/js">$(function () {$('#<%= ButtonEmail.UniqueID %>').button();});</script>
<div id="dialog-modal" title="Cadastro">
<p>Digite seu email para que eviemos o link do cadastro para ele:</p>
<p><asp:TextBox ID="TextBoxEmail" CssClass="ui-corner-all" runat="server"></asp:TextBox>
<asp:Button ID="ButtonEmail" runat="server" Text="Enviar Link" onclick="ButtonEmail_Click" /></p>
<div><asp:Label ID="LabelEmail" runat="server" Text="teste"></asp:Label></div>
</div>
c# code:
protected void ButtonEmail_Click(object sender, EventArgs e)
{
...
}
even when a delete this: $(function () {$('#<%= ButtonEmail.UniqueID %>').button();}); dont work, the button stays with the original design, but dont work
Use this
<script type="text/javascript">
$(function () {
$('#<%= ButtonEmail.ClientID %>').button();
});
</script>
Please note the ClientID which replaced UniqueId. Also ensure that the dependent scripts are loaded (There should be no javascript errors).
After reading some of the comments on the other answer, I'm starting to wonder if possibly it's your server side click event which is not working? In that case you're probably going to have to provide more information and code.
To make an asp.net server side click work in a dialog, ensure that the dialog is part of the form (after its been made into a dialog by jquery. Details are here. jQuery UI Dialog with ASP.NET button postback
may be something like this
var buttonId = <%= ButtonEmail.UniqueID %>;
$(function () {$('#' + buttonId).button();});
i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?
In your java script method raise a __dopostback call to a Server side method.
<script type="text/javascript">
function YourFunction()
{
__doPostBack('btnTemp', '')
}
</script>
Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.
You can have a good understanding of dopostback at DoPostBack Understanding
My aspx page is like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function CallMe() { __doPostBack('btnTemp', '') }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
<div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
And my Server Side code is as:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
protected void btnTemp_Click(object sender, EventArgs e)
{
}
Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.
There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.
I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.
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
I have an asp.net page that contains an Iframe embedded with some data and a ImageButton. On ImageButton click event (server side) I have Response.Redirct:
Response.Redirect("results.aspx");
This always open the results.aspx in iframe. I want that results.aspx should always open in the parent window. I tried the following till now but none worked:
Response.Redirect("<script language='javascript'>self.parent.location='results.aspx';</script>");
Response.Redirect("javascript:parent.change_parent_url('results.aspx');");
As responded by Rifk, I add the ClientScriptManager.
.aspx has this entry:
<asp:ImageButton ID="ImageButton_ok" ImageUrl="~/images/ok.gif"
OnClick="btnVerify_Click" OnClientClick="ValidateFields()"
runat="server" />
Code behind in Page_Load():
ClientScriptManager cs = Page.ClientScript;
StringBuilder myscript = new StringBuilder();
myscript.Append("<script type=\"text/javascript\"> function ValidateFields() {");
myscript.Append("self.parent.location='default.aspx';} </");
myscript.Append("script>");
cs.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", myscript.ToString());
btnVerify_Click has the main business logic. How will I stop OnClientClick() to fire if there my business logic fails? or, how can I fire when server side code is successfully executed?
Response.Redirect will only effect the page in the iFrame if that is the page that is doing the redirect on the server side. You want to run some javascript within that iFrame that will redirect the parent, as you have in your second example. In order to run the script, you shouldn't be using Response.Redirect(), but rather you should be registering client script.
See the following link as to how to register client script in your code in ASP.Net 2.0 -
Using Javascript with ASP.Net 2.0
For example, you would add something similar to this at the end of your event that handles the ImageButton Click:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myUniqueKey",
"self.parent.location='results.aspx';", true);
I have an asp.net page that contains an Iframe embedded with some data and a buttons. On button click event (server side) I have Response.Redirct, but i need to close the Iframe and load the parent page.adding the below mentioned script solved the issue.
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myUniqueKey", "self.parent.location='results.aspx';", true);
Thanks Rifk for the solution. Here is the code for those who have similar issue:
In aspx file, I have defined a new JS function Redirection(). ValidateFields() function will do some client side validations.
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function ValidateFields()
{
alert ("Some client side validations!!");
}
function Redirection()
{
self.parent.location="http://www.google.com";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Content - In IFrame</h2>
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" OnClientClick="return ValidateFields()"
runat="server" style="height: 11px" />
</div>
</form>
</body>
in code behind, I have very simple code that registers clientscriptblock after doing some server side validations. I required that the redirection to happen only if the server side validation is successfull.
bool isValid = false;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnVerify_Click(object sender, EventArgs e)
{
//do some validations
isValid = chkValid.Checked;
if (isValid)
this.Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", "Redirection()", true);
}
You can try this:
Response.Write("<script>window.open('page.aspx','_parent');</script>");
Regards.
Response.Clear();
Header.Controls.Add(new LiteralControl(#"
<script type=""text/javascript"">
top.location = ""/Logout.aspx"";
parent.location = ""/Logout.aspx"";
</script>
"));
If you just want to open a website directly "over" the current page with your iframe (not new tab or window), then you don't need code-behind.
ie:
<asp:LinkButton ID="lnkGeneralEnq" runat="server" OnClientClick="OpenOverFrame();"><strong>click this link</strong></asp:LinkButton>
and a single line Java script bit of code in your ASPX page...
function OpenOverFrame() {
window.open('http://mywebsite.com','_parent');
}