How to simulate MVC routing in WebForm ASP.Net? - asp.net

You all have seen how MVC minifies URL by default in form of url: "{controller}/{action}/{id}". It's done in RouteConfig.cs.
I'm looking for a way so that a webform URL like mywebsite.com/Page/Default.aspx?id=100&Browser=ff changes to mywebsite.com/Page/Default/100?Browser=ff, It should be done in Globa.ascx.
There are some posts in StackOverFlow website which instructs how to redirect a reserved URL to a certain page, it's obvious that my question is something else, I'm looking for a way to offer a pattern in Global.ascx.

At the solution explorer, under your project, add a new ASP.NET item "Global.asax"
Add the using statement:
using System.Web.Routing;
At the Application_Start event, type in your routing URL, for example:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("default1", "Page/Default", "~/Page/Default.aspx");
RouteTable.Routes.MapPageRoute("default2", "Page/Default/{controller}/{action}/{id}", "~/Page/Default.aspx");
}
Then, at the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string controller = RouteData.Values["controller"] + "";
string action = RouteData.Values["action"] + "";
string id = RouteData.Values["id"] + "";
}
}

Related

Intercepting asp.net ajax webmethod

Is there a way to intercept asp.net ajax webmethods(aspx page static methods)?
i want to intercept before request reaching the method and also after sending the response.
use in global.asax file
protected void Application_BeginRequest(Object sender, EventArgs e)
{
//before method colling
string ss = HttpContext.Current.Request.Url.ToString();//use if it is equal to your page webmethod url i.e. domain.com/dfault.aspx/GetMessage;
if(ss=="http://domain.com/dfault.aspx/GetMessage")
{
do your work here
}
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
//after method colling
string ss = HttpContext.Current.Request.Url.ToString();// use if it is equal to your page webmethod i.e. domain.com/dfault.aspx/GetMessage;;
if(ss=="http://domain.com/dfault.aspx/GetMessage")
{
do your work here
}
}
you can try fiddler or HTTtamper.

WCF\ASP.NET interoperability

I have a server application written in WCF using asynchronous callbacks, and a webforms application in ASP.NET.
All of the communication is fine between the 2 applications, I can call the exposed functions in the server via the web application, and the server can send callbacks to the web application, however sometimes the functions within the callback work, and other times, they don't.
For example, I would like a login button on the web app to send a username and password to the server, the server checks this against the database, and if the login information is correct, it should send a callback, which opens a new page in the web app.
Here is the relevant server code:
public void Login(String username, String password)
{
//DoCheckAgainstDatabase(username, password);
ICallback callback = OperationContext.Current.GetCallbackChannel<ICallback>();
callback.LoginSuccess();
}
and the web application code:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
I can put in breakpoints, and see that everything is working fine, it's just that the code 'ScriptManager.RegisterStartupScript...' does not execute properly all the time.
Could this be something to do with threading? Could anyone suggest a way to fix this please?
Thanks in advance!
David
It occurs to me that it's possible your page life cycle may be ending - or at least getting to the Render stage, which is where the start up script would be written to the output - before the callback is called.
Is it possible to call your service synchronously, and not proceed out of LoginButton_Click until the service call returns?
I think you are missing script tag - wrap your window.oppen with it, like
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "<script>window.open('Client.aspx','_self');</script>", true);
Thank you Ann L. for guidance on this. I have added a ManualResetEvent, and then in the button click method, I wait until I have received the callback, then proceed with opening the new page:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
private ManualResetEvent _resetEvent = new ManualResetEvent(false);
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
_resetEvent.WaitOne();
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
_resetEvent.Set();
}

ASP.net passing data between pages

I have a .aspx web page, with a html form within it, this also has two input boxes.
Whats the best way to take the input box data and pass it to a new .aspx page where it is dealt with by the request method.
Assuming that the data is not sensitive then the best method to pass it to your new page using Response.Redirect and the querystring using:
protected void MyFormSubmitButton_Click(Object sender, EventArgs e)
{
string value1 = txtValue1.Text;
string value2 = txtValue2.Text;
// create a querystring
string queryString = "x=" + value1 + "&y=" + value2;
// redirect to the encoded querystring
Response.Redirect("NewPage.aspx?" + Server.URLEncode(queryString));
}
This web page has a lot of information which you can use for passing the values from page to page.
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx#Y1100
Try Server.Transfer:
Terminates execution of the current
page and starts execution of a new
page by using the specified URL path
of the page. Specifies whether to
clear the QueryString and Form
collections.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
Your main page:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// ThreadAbortException occurs here.
// See http://support.microsoft.com/kb/312629 for more details.
Server.Transfer("AnotherPage.aspx", true);
}
}
"AnotherPage.aspx":
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
// Accessing previous page's controls
}
}

ASP.NET: Get Page's filename

I have an ASPX page named Default.aspx. From its codebehind on Page_Load(), I would like to get "Default.aspx", alone, into a string:
protected void Page_Load(object sender, EventArgs e)
{
string aspxFileName = ?;
}
What should I replace ? with—what will get me the ASPX filename?
System.IO.Path.GetFileName(Request.PhysicalPath);
protected void Page_Load(object sender, EventArgs e)
{
string cssFileName = Path.GetFileName(this.Request.PhysicalPath).Replace(".aspx", ".css");
}
Some short answers are already taken so, for fun, and because you'll likely want to do this from other Web Forms, here's an expanded solution that will affect all Web Forms in your project uniformly (includes code to get a filename as requested).
Make an extension method for the System.Web.UI.Page class by putting this code in a file. You need to use .NET 3.5.
namespace MyExtensions {
using System.Web.UI;
static public class Extensions {
/* You can stuff anybody else's logic into this
* method to get the page filename, whichever implementation you prefer.
*/
static public string GetFilename(this Page p) {
// Extract filename.
return p.AppRelativeVirtualPath.Substring(
p.AppRelativeVirtualPath.IndexOf("/") + 1
);
}
}
}
To get the filename from any ASP.NET Web Form (for example in the load method you specified):
using MyExtensions;
protected void Page_Load(object sender, EventArgs e) {
string aspxFileName = this.GetFilename();
}
Call this method on any Web Form in your project.

Accessing Events And Members In The Master Page

I have an event in the Master page that I want to access in the pages that use that master page but it doesn't seem to be working.
In the Master
public delegate void NotifyRequest(object sender, EventArgs e);
public class MyMaster
{
public event NotifyRequest NewRequest;
protected void uiBtnNewTask_Click(object sender, EventArgs e)
{
if(NewRequest!= null)
NewRequest(this, e)
}
}
Inherited Page
MyMaster mm = new MyyMaster();
mm.NewRequest += new NotifyRequest(mm_NotifyRequest);
void mm_NotifyRequest(object sender, EventArgs e)
{
Label1.Text = "Wow";
this.Label1.Visible = true;
}
My problem is the event is always null. Any ideas?
You probably need to use the following syntax to access your event in the Master Page
((MyMaster)Master).NewRequest += new NotifyRequest(mm_NotifyRequest);
If you wish to access members of a master page you need to use the page Master attribute and cast it to your master page.
Alternately
If you wish do not wish to use a cast you can use the #MasterType directive to create a strong reference to your master page, in this case MyMaster. So you would be able to access your event like so: Master.NewRequest.
More Reading about Master Pages

Resources