RouteData.Values stays Empty - c#

My Code for the Route looks like this:
RouteTable.Routes.MapPageRoute("IDP", "Person/{IDP}", "~/Person.aspx")
And now i want to get the Data on a Form, normally it works like this:
int id = Convert.ToInt32(Page.RouteData.Values["IDP"]);
But everytime i try to get the Data from the Route e.g.: http://PC-81/SkillDatenbank/Person/1
I get no Data from the Value (it is empty!)
I am using ASP.Net 4.5 with Web Forms.
Edit: I made an new Project and tested and it didnt work either
What am i Doing wrong? in the Last Project it did work like this :(
Can you help me?

Your problem ist probably located in your Routing table. I have created a WebForms project to test this out.
Open up your Global.asax (or whereever you store your RouteConfig; default is App_Start/RouteConfig.cs) and check your RegisterRoutes method. Add the following line to it, if it isn't already present.
void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
/* ... additional routes */
routes.MapPageRoute("","Person/{IDP}", "~/Person.aspx");
}
In your Application_Start there should be a line like this, if you use the default configuration with in the App_Start folder: RouteConfig.RegisterRoutes(RouteTable.Routes);
If you defined your routes in your global.asax.cs it is just RegisterRoutes(RouteTable.Routes);
If you now access your Page via http://PC-81/SkillDatenbank/Person/1 the RouteData dictionary will contain 1 set of data, like this:

Following code has worked for me, I have moved additional routes to top of the function.
Also, in my case RedirectMode is off because I'm using Jquery in my code and inorder to make a Webmethod work, I have turned off RedirectMode.
void RegisterRoutes(RouteCollection routes)
{
/* ... additional routes */
routes.MapPageRoute("","Person/{IDP}", "~/Person.aspx");
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}

Related

Ignore first segment of url for globalization

I was required to change the way the globalisation works on my project.
Today I have
www.mysite.com.br
www.mysite.com.mx
www.mysite.com.ar
So I could access my pages like: www.mysite.com.br/default.aspx
and based on this, I make my way changing the language and the content, based on the URL
Country obj = dataContext.Country.FirstOrDefault(c => c.Domain.Equals(HttpContext.Current.Request.URL.Host.ToLower()));
But now, they said that they need it to be like this
www.mysite.com/br
www.mysite.com/mx
www.mysite.com/ar
So I need to access my pages like: www.mysite.com/br/default.aspx
I could get the Country on my function by using this
Country obj = dataContext.Country.FirstOrDefault(c => c.Abbreviation.Equals(HttpContext.Current.Request.Url.Segments.Where(s => s != "/").First()));
But when I access www.mysite.com/br/Default.aspx he gives me the error "Server Error in '/' Application The resource cannot be found". Of course, I don't have a Default.aspx inside a folder named br.
I was reading about routes. But so far I couldn't implement those and I'm not sure if this is the right path for me atm
By routes, I'm trying something like this:
Global.asax ( I had to create one, because my project didn't have one )
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{lang}/Default.aspx",
"~/Default.aspx"
);
}
But the error is the same.
I got it to work.
As it is a WebSite not a Project, I had to add RegisterRoutes(RouteTable.Routes); inside Application_Start with the help of this answer

Implicit connection of Action Methods with Views in ASP.NET MVC

I am currently working in a brownfield ASP.NET MVC 3 project in VS2010.
In this project, views and controllers are in separate projects. This is not something that I have seen before. In each action method there is no explicit stating of view name as below.
return View("viewName",passingModel);//projects where controllers and views are in same
I have done this implicitly in VS2012 by right clicking on the view and do add view. So I was not bothered about where is this connection between action method's return view and the view is stated.
Unlike in VS2012, in VS2010 I can not navigate to the view that is related to one particular action method by right clicking on View and doing go to view.
I tried to understand this by doing this small experiment. I created a Controller and created a Action Method call xxxx and I created a view for that implicitly as mentioned above and searched the word xxxx in entire solution but this word only appeared in controller and in the view.
So, I was unsuccessful in finding the answer. I think visual studio itself creating its own mapping to achieve this.
I would like to know who these implicit connections are created among action methods and views to understand what is going on in my project.
Edit:
Both the projects which contains controllers and views are class libraries. not asp.net mvc projects.
Global.aspx file contains this:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
DependenciesHelper.Register(new HttpContextWrapper(Context));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RoutingHelper.RegisterRoutes(RouteTable.Routes);
}
protected void Application_End()
{
//Should close the index
//If this method is not executed, the search engine will still work.
SearchService.CloseIndex();
}
The mapping is fairly straightforward. For example if you have a controller called "MyBrilliantController" and an action method called "MyExcellentAction" which returned just return View(); it would map to (in the UI project) ~/Views/MyBrilliant/MyExcellentAction.cshtml
The only time where this is different is when you are working with "Areas" - but the mapping is effectively the same, it would just consider the area folder first (ie ~/Areas/MyArea/Views/MyBrilliant/MyExcellentAction.cshtml)
Hope that helps.
EDIT - You can also specify namespaces in the global.asax file on each route for the engine to find controllers
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}, // Parameter defaults
new string[] {
// namespaces in which to find controllers for this route
"MySolution.MyControllersLib1.Helpers",
"MySolution.MyControllersLib2.Helpers",
"MySolution.MyControllersLib3.Helpers"
}
);
}

RDLC Alternating rows

I've been working on an MVC3 app and a recent requirement is that it has a couple of dynamically generated reports. So I added a single webbform with a reportviewer and a couple of reports (.rdlc). But when I try to set Conditional row-fills eg
=IIf(RowNumber(Nothing) Mod 2, "Blue", "Red") // Won't acctually use those colors but you get the gist
But the resulting background is still white.
I tried out the exact same webform in a true blue Webform application and from there it rendered properly. I've checked that my MVC project contains every reference used in my Webforms testproject and added .aspx and .rdlc to ignored routes in 'Global.asax.cs'.
Why the Hybrid Horror?
I can not change from Clientside Reporting generation to Serverside due to Performance Reasons, nor can I use a different/remote server because the environments (yes plural) lack of bandwidth and connectivity. And I'd prefer not having to add a separate app pool just for the reportviewer (again performance issues).
EDIT1:
Global.asax
public class MvcApplication : System.Web.HttpApplication {
public static void RegisterGlobalFilters ( GlobalFilterCollection filters ) {
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes ( RouteCollection routes ) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.rdlc/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start () {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Report.aspx
....
</rsweb:ReportViewer>
<asp:XmlDataSource ID="reportsDS" runat="server"
DataFile="~/Reporting/ReportSettings/Reportlist.xml"
XPath="Reports/Report" />
<asp:ScriptManager ID="scriptmanager" runat="server" />
....
Report.aspx.cs
// Some configuration initialization and the regular Page_Init + Page_Load assigning
// default values
protected void changeReport() {
ReportViewer.Reset();
ReportDataSource RDS = new ReportDataSource( /* grabbed from a combination of applicationsettings and input parameters */
ReportViewer.LocalReport./* adding datasource and setting paths, names, etc. */
}
EDIT2:
Added the code to give better context to what I'm doing but seeing that the Code acctually works when published from a Webforms project I'm guessing that ReportViewer performs some sort of Blackmagic requests that the Global.asax isn't particularly fond of. But despite my best firebug efforts I haven't been able to find that brand of magic yet.
I managed to solve the problem by modifying the Page_Init
protected void Page_Init( object sender, EventArgs e ) {
...
ReportViewer.LocalReport.SetBasePermissionsForSandboxAppDomain(new PermissionSet(PermissionState.Unrestricted));
...
}
Feels like a hack, so I'll hold of a day or two before accepting this answer

ASP.NET 4.0 Routing and Default.aspx (How write A Handler? Is It Necessary Or Not)

i want to route Default.aspx to another URL when page starts.
my global.asax is like this :
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"Default", // Route name
"My Site", // URL with parameters
"~/Default.aspx" // Parameter defaults
);
}
should i write a handler for my purpose?
(i found some samples for .net 3.5 and MVC but what about .net 4 web forms)
if yes how can i write it?
EDIT:
what this line exactly do?
routes.Add("Default", new Route(string.Empty, new RouteHandler("~/Default.aspx")));
i am using web forms -> Not MVC
thanks in advace
Here's a specific example of how to deal with routing on asp.net 4.0 web forms (it's just under the mvc part).
http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx
The way you are approaching it is fine. You do have an error in the second parameter of your route. Well perhaps not an error, I dislike spaces in urls as they are actually the encoded spaces. Check out the guide.
Just noticed your edit.
Adding the route essentially creates a mapping between a url or url pattern (which you have as string.Empty which is a problem) and a handler which serves the request(You specify RouteHandler which I don't believe actually exists?). .net Provides a PageRouteHandler which allows you to specify which page responds to your request and deal with a couple other details like security defined on the physical structure of your site. Internally, MapPageRoute is simply calling routes.Add but using the PageRouteHandler.

Get all routes defined in global.asax

I am using webformrouting in my asp.net c# application.
In my global.asax file i define a couple of routes.
My question is, how can i get a list of all routes defined from code behind (on a page)?
You can access the Routes property on the RouteTable
System.Web.Routing.RouteTable.Routes;
I create a partialView to visualize these in the site to help me from time to time (debugging).
#{
var routes = RouteTable.Routes;
}
#foreach (var route in routes)
{
var r = (System.Web.Routing.Route)route;
<h4>#r.Url</h4>
}

Categories