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
Related
I am new to C# and ASP.NET. I have a jQuery yes/no dialog that calls serverside methods (code-behind) using postback.
I put the code together using some snippets I've found on the internet, but I don't fully understand how the code is working.
If I click "yes" in the jQuery dialog, then the server-side C# method DeleteConfirmedServerside is called.
However I don't understand why it works because in the rendered html code I don't see a reference to the server-side method.
I've read some articles about javascript postback... but still I don't understand why the following code works:
.aspx file
// jQuery code (Dialog with yes/no Buttons)
buttons: [
{
id: "Yes",
text: "Yes",
click: function ()
{
$("#btnDeleteConfirmedClientside").click();
}
},
....
<asp:Button ID="btnDeleteCanceledClientside" runat="server"
OnClick="DeleteCanceledServerside" Text="DeleteCanceled"
UseSubmitBehavior="false" style="display:none"/>
<asp:Button ID="btnDeleteConfirmedClientside" runat="server"
OnClick="DeleteConfirmedServerside" Text="DeleteConfirmed"
UseSubmitBehavior="false" style="display:none" />
<div id="myDialog" style="display: none" >
Do you want to delete this record?
</div>
Code-behind (server side)
protected void DeleteConfirmedServerside(object sender, EventArgs e)
{
// called by postback from clientside
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Delete confirmed (YES).')", true);
}
Rendered HTML client side:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
...
<input type="button" name="btnDeleteCanceledClientside" value="DeleteCanceled"
onclick="javascript:__doPostBack('btnDeleteCanceledClientside','')"
id="btnDeleteCanceledClientside" style="display:none" />
<input type="button" name="btnDeleteConfirmedClientside" value="DeleteConfirmed"
onclick="javascript:__doPostBack('btnDeleteConfirmedClientside','')"
id="btnDeleteConfirmedClientside" style="display:none" />
<div id="myDialog2" style="display: none" >
Do you want to delete this record?
</div>
If the user clicks "yes" in jQuery dialog, then btnDeleteConfirmedClientside is "clicked" and then __doPostBack('btnDeleteConfirmedClientside&...) is called (at least this is what I understand)
What I don't understand is this in the rendered html:
onclick="javascript:__doPostBack('btnDeleteConfirmedClientside','')
Why is __doPostBack using btnDeleteConfirmedClientside and not the server-side code-behind method DeleteConfirmedServerside?
DeleteConfirmedServerside is called - but how is this happening, since nowhere in the HTML I see a reference to serverside methods... so how is the C# code-behind method DeleteConfirmedServerside called ?
The __doPostBack javascript method makes a post back to the server, effectively requesting that your server side method be called.
The hanlding of this HTTP post request is handled behind the scenes and calls your server side method.
If you're new to asp.net, I recommend that you start by having a look at http://www.asp.net/mvc and use asp.net mvc rather than asp.net webforms which is what you're using. MVC is the latest and greatest and has many advantages over webforms.
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.
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.
In a simple ASP page, TextBox AutoPostBack events will prevent Button click events (except where button is tapped very quickly) and AutoPostBack events for other controls (like ListBox).
There's a similar question here, but I wasn't happy with being forced to use client side or AJAX solutions: Have to click button twice in asp.net (after autopostback textbox)
Example ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="temp.aspx.cs" Inherits="temp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="PostBack"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="PostBack">
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox><br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="338px"></asp:TextBox></div>
</form>
</body>
</html>
C# code behind:
public partial class temp : System.Web.UI.Page
{
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
}
I've been able to partially solve this problem for buttons by using mousedown instead of click events to submit the form (I also blocked extra AutoPostBack events client-side and handled any extra field changes during button click events server side)
However, this means my buttons aren't quite behaving in the standard (click on release) way.
Is there a better solution to this problem that doesn't require trying to do everything in javascript client-side? (I'm writing a lot of code that reads server data during these postbacks, so javascript isn't an ideal solution.)
I'm also trying to avoid switching to an AJAX library for these pages since every new library I add has to go through security auditing etc.
Note: I'm currently working with ASP.Net 2.0/VS 2005, but if this type of problem is fixed in a later release that would be a compelling argument to upgrade. (As far as I understand it, the same problem seems to happen in ASP.Net 4/VS 2010)
The reason to set AutoPostBack="true" on a field (or other input control) is because you want the page to postback when that control's data changes - without requiring that the user click a button. It sounds like that is exactly what is happening: when the field loses focus, the page does a postback.
Perhaps I'm misunderstanding the question? Can you provide some more information about how you need the page/form to behave?
Edit: more info, based on comment from OP.
I think I understand: the "normal" case is they select something from a DropDownList1, and you autopostback to set the values of DropDownList2, based on the selected item in DropDownList1. However, the user may not care about the second list; if they click "search", you want the button-click to essentially abort the autopostback (already in progress), and initiate a new postback.
Unfortunately, I don't think there's any functionality in any version of ASP.NET to "abort" a postback already in progress (not from the client-side code, anyway). Therefore, in order to implement the above behavior, you're going to have to do something outside the standard ASP.NET postback behavior. Here's a few ideas, though by no means is it an exhaustive list:
Use AJAX and JS to retrieve the contents of DropDownList2. If the user clicks search while that ajax call is in progress, the page should postback right away.
Store all possible DropDownList2 data in JSON format in your page; use purely client-side JS to populate List2 when List1 changes. Again, if the user clicks "search", the page will postback right away. Depending on how big the pool of possible List2 entries is, this may bloat the page size too much to be workable.
Use client-side JS to disable your search button when List1 changes selection. The user won't be able to click "search" until the autopostback (to fill List2) completes.
Hope this helps!
To make the client side be more interactive and reduce sending all that viewstate and redrawing the page, I add a little jquery into the mix. It makes things like what you are proposing possible. jquery even ships with the asp.net MVC framework so there is no shame in using it with asp.net.
Here is a simple example that uses jquery that demonstrates what I think you want.
First, in the aspx file, add in a reference to the jquery library. I use the
Google content delivery network so you don't even have add this file to your VS project.
Then take the auto postback references out of all your server controls except the button. I left that one to continue doing a postback because I suspect at some point you want a regular post back, all the other controls use ajax to get your server side response.
I started by using your example page with these modifications:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="temp.aspx.cs" Inherits="temp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
// Establish where the output goes.
var outputObject = $("#<%=TextBox2.ClientID %>");
// create a function to do an ajax postback
function doAjaxPostback(sender, value) {
$.ajax({
type: "POST",
url: "temp2.aspx",
data: "id=" + sender.attr("id") + "&value=" + value,
success: function (data) { outputObject.append("<br />" + data) }
});
}
// Use jquery to wire up the event handler. We use the ClientID property in case these
// elements get embeded in some other server control container later.
$("#<%=TextBox1.ClientID %>").keyup(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=TextBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
$("#<%=ListBox1.ClientID %>").change(function (event) { doAjaxPostback($(this), $(this).val()); });
// Use a plain html button tag for ajax only. The server control button gets rendered as
// a submit button which requires it to be handled a little differently.
$("#PlainButton").click(function (event) { doAjaxPostback($(this), $(this).attr("value")); event.preventDefault(); });
});
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="PostBack" Text="Button" /><br />
<button id="PlainButton" value="Plain Old Button">Ajax Only, No postback</button>
<br />
<asp:ListBox ID="ListBox1" runat="server" >
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
</asp:ListBox>
<br />
<br />
Events Fired:<br />
<asp:TextBox ID="TextBox2" runat="server" Height="159px" TextMode="MultiLine" Width="438px"></asp:TextBox>
</div>
</form>
</body>
</html>
Then for the code behind I just made a tiny change so we can report when we get a regular postback versus the ajax kind:
protected void PostBack(object sender, System.EventArgs e)
{
this.TextBox2.Text += "\n\nGot an asp.net postback\n\n"
+ string.Format("PostBack for - {0}\n", ((System.Web.UI.Control)sender).ID);
}
Okay, so I was trying not to get too fancy but I wanted to demonstrate how easy this is so I made a second page, temp2.aspx but left the aspx file alone as i only needed what is in the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class temp2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = string.Empty;
string value = string.Empty;
Response.Clear();
if (Request.Form == null || Request.Form.Count < 1)
{
Response.Write("I got nothin'");
Response.Flush();
Response.End();
return;
}
id = Request.Form["id"];
value = Request.Form["value"];
Response.Write(string.Format("\nevent from: {0}; value={1}",id,value));
Response.Flush();
Response.End();
}
}
}
Notice that what I did was clear, write, flush and end the response so only the text we want is sent back to the caller. We could have done some fancy stuff in the page_load of the original temp page to check if it is a call from the ajax function that will not clear or flush the response if the incoming Request.Form does not contain a certain field, etc. But by doing it as a separate page, I hoped to simplify the code. This also opens up possibilities.
Say you have a country drop down that has Canada and USA in it and when it changes, you want to sent back data to populate a State/Province dropdown with the appropriate values. By putting the lookup code on its own page the way I did with temp2.aspx, you can then call it from all the pages in your app that have a need for such a service.
Good luck, let me know if you have any trouble understanding my code.
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');
}