Asp.net mvc. Routing with trailing slash - asp.net-mvc

I want to have two routes, for example:
http://localhost:1227/Product
and
http://localhost:1227/Category/
trailing slash is the only difference.
In first case I want to show information about product in other case about category. "Product" and "Category" are names of some products or categories
Is it possible to implement?
My approach:
Routes:
routes.MapRoute("category route", "{name2}", new { controller = "test", action = "GoToView2" }, new { name2 = ".*/?" });
routes.MapRoute("product route", "{name}", new { controller = "test", action = "GoToView1"});
Controller:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
return View();
}
public ActionResult GoToView1(string name)
{
// call to db to get some information about product
return View((object) name);
}
public ActionResult GoToView2(string name2)
{
// call to db to get some information about category
return View((object)name2);
}
}
Index View:
......
<br/>
Show proudct
<br/>
Show category
......
But I see that only "GoToView2" is called for two link.
Any ideas how to fix it?
Thanks,

Why would one wants to do that? in your case you have to completely different controller, namely Product and Category and two different action, and even if we could implement the same URL to call different action based on slash, it would be a code smell(bad design), in your case you can simply call TestController/GoToView1 and TestController/GoToView2, if this is not the case, tell us exactly what problem you are trying to solve, maybe there would be a better approach.

Related

Redirect with ASP.NET MVC MapRoute

On my site, I have moved some images from one folder to another.
Now, when I receive a request for old images '/old_folder/images/*' I want to make a permanent redirect to new folder with these images '/new_folder/images/*'
For example:
/old_folder/images/image1.png => /new_folder/images/image1.png
/old_folder/images/image2.jpg => /new_folder/images/image2.jpg
I have added a simple redirect controller
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent(path);
}
}
Now I need to setup proper routing, but I don't know how to pass the path part to the path parameter.
routes.MapRoute("ImagesFix", "/old_folder/images/{*pathInfo}", new { controller = "Redirect", action = "Index", path="/upload/images/????" });
Thanks
I would do in next way
routes.MapRoute("ImagesFix", "/old_folder/images/{path}", new { controller = "Redirect", action = "Index" });
and in controller like that
public class RedirectController : Controller
{
public ActionResult Index(string path)
{
return RedirectPermanent("/upload/images/" + path);
}
}
first download and install RouteMagic package from this link , then redirect your old address to the new address Like the below code :
var NewPath = routes.MapRoute("new", "new_folder/images/{controller}/{action}");
var OldPath = routes.MapRoute("new", "old_folder/images/{controller}/{action}");
routes.Redirect(OldPath ).To(NewPath );
for more information please check out the following link
Redirecting Routes To Maintain Persistent URLs
Answer above using RouteMagic is a good idea, but the example code is wrong (it's included in Phil's post as a bad example).
From the RouteMagic Github demo site global.asax.cs:
// Redirect From Old Route to New route
var targetRoute = routes.Map("target", "yo/{id}/{action}", new { controller = "Home" });
routes.Redirect(r => r.MapRoute("legacy", "foo/{id}/baz/{action}")).To(targetRoute, new { id = "123", action = "index" });
If you specify two routes, you will be setting up an extra mapping that will catch URLs which you don't want.

ASPMvc Routing Issues with legacy url

I have got a legacy url that I cannot change, which is output on a page which needs to now post to a new MVC version of the page:
http://somesite.com/somepage?some-guid=xxxx-xxxx
Now I am trying to map this to a new controller but I need to get the some-guid into my controller:
public class MyController : Controller
{
[HttpGet]
public ActionResult DisplaySomething(Guid myGuid)
{
var someResult = DoSomethingWithAGuid(myGuid);
...
}
}
I can change the controller and routes as much as I like, however the legacy url cannot change. So I am a bit stumped as to how I can get access to the some-guid.
I have tried routing with the ?some-guid={myGuid} but the routing doesn't like the ?, so then I tried to let it autobind, but as it contains hyphens it doesn't seem to bind. I was wondering if there was any type of attribute I could use to hint that it should bind from a part of the querystring...
Any help would be great...
I would have thought you would have done a route a bit like this..
routes.MapRoute(
"RouteName", // Name the route
"somepage/{some-guid}", // the Url
new { controller = "MyController", action = "DisplaySomething", some-guid = UrlParameter.Optional }
);
The {some-guid} part of URL matches your url parmater and passes it to the controller.
So if you have your action like so :
public ActionResult DisplaySomething(Guid some-guid)
{
var someResult = DoSomethingWithAGuid(some-guid);
...
}
Give that a go and see how you get on..
routes.MapRoute(
"Somepage", // Route name
"simepage", // URL with parameters
new { controller = "MyController", action = "DisplaySomething"
);
And then in your controller:
public class MyController : Controller {
public ActionResult DisplaySomething(Guid myGuid)
{
var someResult = DoSomethingWithAGuid(myGuid);
...
}
}
Try this:
routes.MapRoute("SomePageRoute","Somepage",
new { controller = "MyController", action = "DisplaySomething" });
And then in your controller:
public ActionResult DisplaySomething() {
Guid sGuid = new Guid(Request.QueryString["some-guid"].ToString());
}

How can map an asp.net MVC route with more than 3 components?

I'm trying to learn asp.net mvc, and almost everywhere I see route description with three components like /Controller/Action/{anyParams}
I'd like to know if I can map a route similar to,
/Folder(or namespace)/Controller/Action/params...
ex:
/Admin/Student/Edit/id
/ABC/Faculty/Add/`
/XYZ/Student/Edit/id
or in general,
/XYZ/Controller1/Action/{param}
Yep the second parameter in the MapRoutes function (usually in Global.asax.cs is Url and this can be any pattern you want. something like
routes.MapRoute("MyRoute", "XYZ/Controller1/Action/{param}",
new {controller = "Controller1", action = "Action"}});
should do the trick.
You can make your routes as complex as you want.
F.e. the following route:
routes.MapRoute("some-route", "products/detail/order/{id}/{name}/",
new { controller = "Products", action = "Order" },
new { id = "^\d+" });
will route to the following function:
public class ProductsController : Controller {
public ActionResult Order (int id, string name) {
}
}
So you can specify as many parameters as you want, and they will be passed into your action as function parameters.

Pretty URL ASP.NET MVC

How can I get pretty urls like localhost:8888/News/Example-post instead of localhost:8888/Home/Details/2
My HomeController has the following for the Details method
public ActionResult Details(int id)
{
var ArticleToView = (from m in _db.ArticleSet where m.storyId == id select m).First();
return View(ArticleToView);
As the ASP.NET routing system is somewhat complicated, there are many ways to accomplish what you describe.
First of all, do you just want to have a pretty URL for the Details method? If so, you might consider renaming HomeController to NewsController or moving the Details method into a new NewsController class - that will automatically form the /News part of the URL. If you don't want a /Details part, you might rename your Details method Index, as that will be automatically called by /News. Finally, you need to change your int id parameter into string name.
If you want many custom URLs, you're going to have to define your own routes. Here are two ways of doing this:
1.
The easiest way I've found is to use an ASP.NET MVC Attribute-Based Route Mapper. That way, all you have to do is add an attribute on each method you want a pretty URL for and specify what URL you want.
First, you must follow a few steps to set up the attribute-based route mapping system, as outlined on that link.
After completing those steps, you must change your method to look like this:
[Url("News/{name}")]
public ActionResult Details(string name)
{
var ArticleToView = (from m in _db.ArticleSet where m.storyName == name select m).First();
return View(ArticleToView);
}
2.
Alternatively, you can define your custom routes manually in Global.asax.cs. In your RegisterRoutes method, you can add the following in the middle:
routes.MapRoute(
"NewsDetails",
"News/{name}",
new { controller = "News", action = "Details", name = "" }
);
What I do on my sites is that I check the URL against either the Page Title or Page Stub in cases where the page titles could have the same name for instance if you have a site that posts a "Picture of the Week" you may want to use a stub instead of title as you'll have multiples named the same thing.
URLs look like this: http://mySite.com/Page/Verse-of-the-Week
Global.asax contains this:
routes.MapRoute("Pages", "{controller}/{pageID}", new { controller = "Page", action = "Index", pageID = "Home" });
PageController is this:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string pageID)
{
if (pageID == null)
{
pageID = pageRepository.HomeOrLowest();
}
var p = pageRepository.ByStub(pageID);
if (p == null) { return RedirectToAction("NotFound", "Error"); }
return View(p);
}
The repository looks like this:
private static Func<mvCmsContext, string, Page> _byStub =
CompiledQuery.Compile((mvCmsContext context, string pageTitle) =>
(from p in context.Pages
where p.pageTitle.Replace(" ", "-") == pageTitle
select p).SingleOrDefault());
public Page ByStub(string pageTitle)
{
return _byStub(context, pageTitle);
}
I hope that helps.
Edit to add duplicate handling:
private static Func<mvCmsContext, string, int> _pageExists =
CompiledQuery.Compile((mvCmsContext context, string pageTitle) =>
(from p in context.Pages
where p.pageTitle.Replace(" ", "-") == pageTitle
select p).Count());
public bool PageExists(string pageTitle)
{
return Convert.ToBoolean(_pageExists(context, pageTitle));
}
Validates like this:
IValidationErrors errors = new ValidationErrors();
if (CreateOrEdit == "Create")
{
if (pageRepository.PageExists(model.pageTitle) && !String.IsNullOrEmpty(model.pageTitle))
errors.Add("pageTitle", "A page with this title already exists. Please edit it and try again.");
}
Please check out this package I've created: https://www.nuget.org/packages/LowercaseDashedRoute/
And read the one-line configuration here: https://github.com/AtaS/lowercase-dashed-route

View Called from Partial Not Submitting Form Data

I hope I am able to put this question together well.
In a partial view I have a link to a create action:
public ActionResult CreateProject()
{
return View("EditProject", new Project());
}
Now this loads another view which allows editing of the blank model passed to it. But when form is submitted it is supposed to post to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditProject(Project record)
{
if (ModelState.IsValid)
{
projectRepo.saveProject(record);
return View("Close");
}
else
{
return View("EditProject");
}
}
This method works for many of the tables and edit actions work just as well for the same view. But only for the create action (with the blank model) the form keeps calling to the create action, as I traced with the debugger.
One of my team mates has solved this problem so:
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult EditProject(int id)
{
Project project = null;
if (id == 0)
{
project = new Project();
}
else
{
project = (from p in projectRepo.Projects
where p.ProjectID == id
select p).First();
}
return View(project);
}
And in the partial instead of having <%= Html.ActionLink("Create New", "CreateProject")%> there'd be <%= Html.ActionLink("Create New", "CreateProject", new { id = 0 })%>.
Now I was hoping to find out why the previous method would not go through, since it does for other tables in other views. Thanks.
By default your form will post to same URL it was rendered at. Since you called create action it will post back to create action, and not edit, 'cos views do not matter (-:
Explicitly use
<%= using( Html.BeginForm("Action","Controller) ){ %>

Resources