asp.net multiple urls pointing to same controller - c#

I am working on a social networking site where we are implementing profiles, pages, groups etc. At this stage, we are working with profiles and pages. They both have wall where user can put some status, pics etc, more like facebook wall.
Now a controller WallController can be accessed by two different urls.
www.mysite.com/profile/121/some-user/wall
and
www.mysite.com/page/222/some-page/wall
On the left hand side of the page, I load some basic information (name etc) and a menu.
saying
www.mysite.com/profile/121/some-user/photos
www.mysite.com/profile/121/some-user/videos
www.mysite.com/profile/121/some-user/songs
This applies to both (page and profile).
here is my route for page
routes.MapRoute(
"Page-wall", // Route name
"page/{id}/{name}/wall", // URL with parameters
new { controller = "wall", action = "details", id = "", name = "" },
new { id = #"\d+" },
new string[] { "PagesNameSpace.Controllers" } // Parameter defaults
);
and for profile
routes.MapRoute(
"profile-wall", // Route name
"profile/{id}/{name}/wall", // URL with parameters
new { controller = "wall", action = "details", id = "", name = "" },
new { id = #"\d+" },
new string[] { "ProfileNameSpace.Controllers" } // Parameter defaults
);
Now, the problem is, I have to identify what object is accessing the url. here is my WallController
public class WallController : Controller
{
public ActionResult Details(long id, string name)
{
return View(LoadWallData(id));
}
}
I see a route value dictionary as a solution, but would like to see, what is the best solution for this kind for situations.
help will be appreciated.
Regards
Parminder

I would probably do the following, you just add the values into your routes:
Change your controller:
public class WallController : Controller
{
public ActionResult Details(long id, string name, string obj)//added param
{
return View(LoadWallData(id));
}
}
And then your routes:
routes.MapRoute(
"Page-wall", // Route name
"page/{id}/{name}/wall", // URL with parameters
new { controller = "wall", action = "details", id = "", name = "",
/*See this>>>> */ obj="page"},
new { id = #"\d+" },
new string[] { "PagesNameSpace.Controllers" } // Parameter defaults
);
routes.MapRoute(
"profile-wall", // Route name
"profile/{id}/{name}/wall", // URL with parameters
new { controller = "wall", action = "details", id = "", name = "",
/*See this>>>> */ obj="profile" },
new { id = #"\d+" },
new string[] { "ProfileNameSpace.Controllers" }
);

using ((System.Web.Routing.Route)(Url.RequestContext.RouteData.Route)).Url you can get the URL with parameter values from MapRoute.

I feel, I would go with this approach.
public class WallController : Controller
{
public ActionResult Details(string type ,long id, string name)//added param
{
return View(LoadWallData(id));
}
}
and my routes
routes.MapRoute(
"wall-default", // Route name
"{type}/{id}/{name}/wall", // URL with parameters
new { controller = "wall", action = "details", id = "", name = "",
type="profile"},
new { id = #"\d+" },
new string[] { "PagesNameSpace.Controllers" } // Parameter defaults
);
Now just by passing the type parameter, I can get action link for page and profile.
thanks a lot to everyone.
Regards

Related

HttpVerbs.Get and parameters?

I have the following action :
public class IntegrationController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ContentResult Feed(string feedKey)
{
...
}
}
I have tried to use this URL :
http://MyServer/Integration/Feed/MyTest
but feedKey is null? Does this have something to do with routes?
Edit 1 :
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Ad", action = "List", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"TreeEditing", // Route name
"{controller}/{action}/{name}/{id}", // URL with parameters
new { controller = "AdCategory", action = "Add", name = string.Empty, id = -1 }
);
Edit 2 :
routes.MapRoute(
"IntegrationFeed", // Route name
"{controller}/{action}/{name}/{feedKey}", // URL with parameters
new { controller = "Integration", action = "Feed", name = string.Empty, feedKey = "" }
);
Do you have a route defined for feedKey? Using the default routes, the following should work (change feedKey to id).
[AcceptVerbs(HttpVerbs.Get)]
public ContentResult Feed(string id)
{
// ...
}

How can I add a route in controller

I'd like to map a new route after I commit a new object to db. So for example if i enter object with name "Test" I would like to have a new route immediately, to resolve "Test.aspx".
I tried
System.Web.Routing.RouteTable.Routes.MapRoute(obj.NameUrl, obj.NameUrl + extension, new { controller = "per", action = "Index", name = obj.NameUrl });
in controller but it does not work (no error, just probably not right time in life cycle?). Same code works in Application_Start()
You should avoid registering routes dynamically. The following static route in your Application_Start should be able to handle your scenario of having dynamic route parameters:
routes.MapRoute(
"page",
"{name}.aspx",
new { controller = "per", action = "index" },
new { name = #"[a-z0-9]+" }
);
and if the extension has to be dynamic as well:
routes.MapRoute(
"page",
"{name}.{extension}",
new { controller = "per", action = "index" },
new { name = #"[a-z0-9]+", extension = #"[a-z]{3,4}" }
);
and then you could have the Index action to handle requests to this route:
public class PerController: Controller
{
public ActionResult Index(string name, string extension)
{
...
}
}
and if you want to generate a link to this action:
#Html.RouteLink("go to foo", "page", new { name = "foo", extension = "aspx" })

Creating an Html.ActionLink to a dynamic content page

I have functionality on my site to create/edit/delete pages for the front end. Here's my controller:
namespace MySite.Controllers
{
public class ContentPagesController : Controller
{
readonly IContentPagesRepository _contentPagesRepository;
public ContentPagesController()
{
MyDBEntities entities = new MyDBEntities();
_contentPagesRepository = new SqlContentPagesRepository(entities);
}
public ActionResult Index(string name)
{
var contentPage = _contentPagesRepository.GetContentPage(name);
if (contentPage != null)
{
return View(new ContentPageViewModel
{
ContentPageId = contentPage.ContentPageID,
Name = contentPage.Name,
Title = contentPage.Title,
Content = contentPage.Content
});
}
throw new HttpException(404, "");
}
}
}
And in my global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Page", // Route name
"Page/{name}", // URL with parameters
new { controller = "ContentPages", action = "Index" }, // Parameter defaults
new[] { "MySite.Controllers" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new[] { "MySite.Controllers" }
);
}
So I have a dynamic page in my database, named About. If I go to mysite.com/Page/About, I can view the dynamic content.
I want to create an ActionLink to this page. I've tried it like this:
#Html.ActionLink("About Us", "Index", "ContentPages", new { name = "About" })
But when I look at the link on the page, the url just goes to the current page with Length=12 in the query string. For instance, if I'm on the homepage, the link goes to mysite.com/Home?Length=12
What am I doing wrong here?
You are not using the correct ActionLink overload. Try like this:
#Html.ActionLink(
"About Us", // linkText
"Index", // action
"ContentPages", // controller
new { name = "About" }, // routeValues
null // htmlAttributes
)
whereas in your example:
#Html.ActionLink(
"About Us", // linkText
"Index", // action
"ContentPages", // routeValues
new { name = "About" } // htmlAttributes
)
which pretty obviously explains why your doesn't generate the expected link.

Language in URL, Routing and Areas

I've learned so far how to set up a correct routing if I would like to have the language within the URL, e.g. .../en/MyController/MyMethod. With the following routing this works great so far:
routes.MapRoute("Default with language", "{lang}/{controller}/{action}/{id}",
new
{
controller = "Report",
action = "Index",
id = UrlParameter.Optional,
}, new { lang = "de|en" });
// Standard-Routing
routes.MapRoute("Default", "{controller}/{action}/{id}", new
{
controller = "Report",
action = "Index",
id = UrlParameter.Optional,
lang = "de",
});
Now I Inserted a new area Cms, and I call AreaRegistration.RegisterAllAreas(); in Application_Start().
As soon as I call a controller within this area, I miss the language-key:
MvcHandler handler = Context.Handler as MvcHandler;
if (handler == null)
return;
string lang = handler.RequestContext.RouteData.Values["lang"] as string;
How could I make the above routing work with areas?
Thx for any tipps, sl3dg3
Check out the generated class that derives from AreaRegistration, named [AreaName]AreaRegistration.
It contains a route registration as well, this is the default:
context.MapRoute(
"AreaName_default",
"AreaName/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
The following routing works now in my case (the area is called Cms):
using System.Web.Mvc;
namespace MyProject.Areas.Cms
{
public class CmsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Cms";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("Cms_default_with_language", "Cms/{lang}/{controller}/{action}/{id}", new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
lang = "de",
}, new { lang = "de|en" });
context.MapRoute(
"Cms_default",
"Cms/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional, lang = "de" }
);
}
}
}
The only thing I'm not quite happy about: now I have more or less duplicate code in Global.asax and in this class. Is there a way to avoid these duplicate mappings?

asp.net mvc routing issues

I haved added this routing to my global asax.
routes.MapRoute(
"News", // Route name
"News/{timePeriod}/{categoryName}/{page}", // URL with parameters
new { controller = "News", action = "Index",
timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
new { page = #"^\d{1,3}$" }// Parameter defaults
);
routes.MapRoute(
"News2", // Route name
"News/{categoryName}/{page}", // URL with parameters
new { controller = "News", action = "Index",
timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
new { page = #"^\d{1,3}$" }// Parameter defaults
);
The problem is urls like /News/add wont work (unless i add the specific route)
is there a better way without having to specify url action in global asax?
I think, that would catch it. But only, if you won't pass any extra arguments like id (because, then it's very similar to News2 route).
routes.MapRoute(
"News0",
"News/{action}",
new { controller = "News", action = "Index" }
);
Also, try Routing Debugger to test for effect you want:
link
Your two routes above will each route to the News controller and hit the "Index" action. If you don't have overloads for the Index action that will take the parameters you are specifying then the route won't work properly. For instance, you should have these two actions:
public ActionResult Index(TimePeriod timePeriod, string categoryName, int page) {..}
public ActionResult Index(string categoryName, int page) {..}
Also, you should remove the default parameter of TimePeriod from your second route since you aren't using it in the route itself:
routes.MapRoute(
"News2", // Route name
"News/{categoryName}/{page}", // URL with parameters
new { controller = "News", action = "Index", categoryName = "All", page = 1 },
new { page = #"^\d{1,3}$" }// Parameter defaults
);
I would recommend having an action for every category instead of creating a route for each category. You could simplify your routes to this:
routes.MapRoute(
"News", // Route name
"News/{action}/{timePeriod}/{page}", // URL with parameters
new { controller = "News", action = "Index", timePeriod = TimePeriod.AllTime, categoryName = "All", page = 1 },
new { page = #"^\d{1,3}$" }// Parameter defaults
);
Then having an action for each category:
public ActionResult All(TimePeriod timePeriod, string categoryName, int page) {..}
public ActionResult Sports(TimePeriod timePeriod, string categoryName, int page) {..}
public ActionResult Weather(TimePeriod timePeriod, string categoryName, int page) {..}
This way all you will need is the one route.

Categories

Resources