ASP.NET MVC basic routing with parameters - asp.net-mvc-3

I have been trying to learn ASP.NET MVC 3 and things are going well apart from the routing aspect, whatever I try I just can't seem to get them quite right.
I have an ActionLink on the main page:
#Html.ActionLink("Contracts", "List", "Contract",
new { User.Identity.Name, page=1 })
Which is meant to access this method in the ContractController:
public ViewResult List(string user, int page = 1)
{
//snip
}
My routes are:
routes.MapRoute(
null,
"Page{page}",
new { Controller = "Contract", action = "List" }
);
routes.MapRoute(
null,
"Page{page}",
new { Controller = "Contract", action = "List", user = "", page = 1 }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The link now will return a 404 error as it can't find the action 'List' in the controller 'Home', which obviously means it didn't use either of the first routes.
Everything worked before I tried to add parameters to the ActionLink, so basically, what am I doing wrong?
Thanks very much.

Alex,
You're doing all the other bits absolutely correctly, however the actionlink has a missing parameter, try this for your actionlink:
#Html.ActionLink("Contracts", "List", "Contract",
new { User.Identity.Name, page = 1 }, null)
Adding the null as the final param (htmlAttributes) is all that's missing for you in this scenario (there are 9 overloads for Html.ActionLink, so it's VERY easy to miss the correct implementation).

Related

Orchard cms in mvc 3 application how to remove unwanted url content

Orchard CMS in MVC3 Application.
How to remove the unwanted "url" content?
Example: http://www.xxxxxx.com/HotelsOnly/HotelList/Region?region=2114&total=848
In routes {area,” HotelsOnly”} ,{controller,”HotelList”}
Url How to change or remove this(/HotelsOnly/HotelList)
Example: http://www.xxxxxx.com/Region?region=2114&total=848
Explain how to remove? Please show any Example.
I think you use this type of rout url it's blow
routes.MapRoute(
"Regis", // Route nameRegister
"Test/Artical/Show/{id}", // URL with parameters
new { controller = "Artical", action = "Show", id = UrlParameter.Optional }
in my project i use rout like this it's below
#Html.RouteLink("click", "Regis", 1);
1 i set a default value for example . so my url look like this
http://localhost:xxxx/Test/Artical/Show/1
I remove Test from my url like this it's below
you will change your rout like this
routes.MapRoute(
"Regis", // Route nameRegister
"Test/Artical/Show/{id}", // URL with parameters
new { controller = "Artical", action = "Show", id = UrlParameter.Optional }
);
and after change rout then my url look like this
http://localhost:xxxx/Artical/Show/1
i think this will help you
new RouteDescriptor {
Route = new Route(
"Region",
new RouteValueDictionary {
{"area", "HotelsOnly"},
{"controller", "HotelList"},
{"action", "Index"}
},
new RouteValueDictionary(),
new RouteValueDictionary {
{"area", "HotelsOnly"}
},
new MvcRouteHandler())
},

url parameters missing after adding a comment and redirecting back to blog post

I am teaching myself asp .net mvc3 by creating a blog application. However, I have
problems with comment upload. It is a very subtle error in that everything works when a user leaves a comment. However, the url of the post changes.
So, a blog post has a url
http://localhost:49175/Blog/Details/3/Third-post
This is generated by the url route map here:
routes.MapRoute(
"BlogDetail", // Route name
"Blog/Details/{id}/{urlHeader}", // URL with parameters
new { controller = "Blog", action = "Details", id = UrlParameter.Optional, urlHeader = UrlParameter.Optional } // Parameter defaults
);
Now, when a user leaves a comment - he is directed to a comment controller:
[HttpPost]
public ActionResult Create(BlogDetailsViewModels viewModel)
{
if (ModelState.IsValid)
{
try
{
blogrepository.Add(viewModel.Comment);
return RedirectToAction("Details", "Blog", new { id = viewModel.Comment.BlogID });
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save comment. Try again, and if the problem persits then contact administrator.");
}
}
// If we got this far, something failed, redisplay form
return RedirectToAction("Details", "Blog", new { id = viewModel.Comment.BlogID });
}
}
However, when somebody leaves a comment - he is redirected back to
http://localhost:49175/Blog/Details/3
I know, as of now there is nothing in the RedirectToAction that passes the urlHeader info. However, I have tried a few things like:
return RedirectToAction("Details", "Blog", new { id = viewModel.Comment.BlogID, urlHeader = viewModel.Blog.UrlHeader });
However, it doesn´t seem to work.
This is the blog details controller:
//
// GET: /Blog/Details/5
public ViewResult Details(int id, string urlHeader)
{
var blogs = blogrepository.GetBlog(id);
var recentblogs = blogrepository.FindRecentBlogs(5);
var archivelist = blogrepository.ArchiveList();
BlogDetailsViewModels viewModel = new BlogDetailsViewModels { Blog = blogs, RecentBlogs = recentblogs, ArchiveList = archivelist };
return View(viewModel);
}
I am stuck for days on this.
-- Full route method as requested --
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"BlogDetail", // Route name
"Blog/Details/{id}/{urlHeader}", // URL with parameters
new { controller = "Blog", action = "Details", id = UrlParameter.Optional, urlHeader = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"BlogArchive", // Route name
"Blog/{year}/{month}", // URL with parameters
new { controller = "Blog", action = "Archive" }, // Parameter defaults
new { year = #"\d{4}", month = #"\d{1,2}", } // Parameter constraints
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
If your form does not contains data for viewModel.Blog.UrlHeader, it will be an empty string, even viewModel.Blog may be null.
You can add a parameter to your post action method, like this:
[HttpPost]
public ActionResult Create(BlogDetailsViewModels viewModel, String urlHeader)
And, in your view that renders the form, use this code to generate the form element:
#Html.BeginForm("Create","Blog",new{urlHeader=Model.Blog.UrlHeader})
Alternatively, you can add a hidden input in your form for the urlHeader. In this way, you don't have to do any of previous two updates.
#Html.HiddenFor(m=>m.Blog.UrlHeader)
Either way, make sure your Model.Blog.UrlHeader is not null or an empty string

Optional parameters in MVC3 routing

I am trying to create routes which can apply 1 and 2 type of URLs.
1 - First route will be at the start of application and I want 2 type of URLs that can used to access index page. I cannot hit below route when I have URL with Home at the end instead going to type 2.
http://www.example.com Or http://www.example.com/Home
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index", name = "" }
);
2 - This type of URL is passing "Name" parameter to load contents from DB. I want this URL like
http://www.example.com/Page?name=Contact Or
http://www.example.com/Page?name=Contact&id=22
But I want above URL like
http://www.example.com/Contact Or http://www.example.com/About
Or
http://www.example.com/Contact/22 Or http://www.example.com/About/33
Where
Contact and About are values for "Name" parameter passed in URL. Below is the Route used
routes.MapRoute(
"DynamicPages",
"{name}",
new { controller = "Home", action = "Page" }
);
Here is a possible solution. I am not sure if this is the right way to do this.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//To match http://www.mysite.com
routes.MapRoute(
"RootUrl",
"",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
//To match http://www.mysite.com/Home
routes.MapRoute(
"RootUrlWithAction",
"Home/{action}",
new { controller = "Home", action = "Index" }
);
//To match http://www.mysite.com/Contact Or
// http://www.mysite.com/About Or
// http://www.mysite.com/Contact/22 Or
// http://www.mysite.com/About/33
routes.MapRoute(
"DynamicPages",
"{name}/{id}",
new { controller = "Home", action = "Page",
id = UrlParameter.Optional }
);
// Everything else
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
}
Tested the following routes. Here the site root url is http://localhost:5879/. Refer the output screenshots provided below for each of the below mentioned scenario.
http://localhost:5879/ --> Uses first route map
http://localhost:5879/Home --> Uses second route map
http://localhost:5879/Contact --> Uses third route map
http://localhost:5879/About/33 --> Uses third route map
http://localhost:5879/Home/Page?name=Contact&id=22 --> Uses third route map
http://localhost:5879/Home/Index/2 --> Uses fourth route map
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
Hope that gives you some idea to solve your issue.

Routing without the controller name

I have a few controllers ,
One let say computer controller
It has action for laptop, desktop gadgets
i would like to have pages name :www.MyDomain/laptop (and so on )
and one let say electronic controller
it has action TV, DVD, (and so on )
i would like to have pages name :www.MyDomain/TV (and so on )
Without specifies the controller?
I don’t understand what happen to my question before I can't edit
(I hope the admin will delete it )
You could do this by specifying route constraints:
routes.MapRoute(
"Computers",
"{name}",
new { controller = "Computers", action = "Index", name = UrlParameter.Optional },
new { page = "laptop|desktop" }
);
routes.MapRoute(
"Gadgets",
"{name}",
new { controller = "Electronic", action = "Index", name = UrlParameter.Optional },
new { page = "tv|dvd" }
);
Now /laptop and /desktop will be routed to the Index action of the ComputersController and /tv and /dvd will be routed to the Index action of the GadgetsController.
In your Global.asax.cs:
routes.MapRoute(
"ViewLaptop", // Route name
"/laptop", // URL with parameters
new { controller = "Computers", action = "Laptop" } // Parameter defaults
);
This should do it.

Issue With ViewBag and Routes (MVC 3 - RC2)

I am having an issue with MVC-3 generating outgoing routes for me.
This is the address of the page I am on for both scenarios: http://localhost:1283/Conflict/Create/1200/300
Here are the map routes:
routes.MapRoute(
null, // Route name
"{controller}/{action}/{custId}/{projId}", // URL with parameters
null, // Parameter defaults
new { custId = #"\d+", projId = #"\d+" }
);
routes.MapRoute(
null, // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Scenario 1:
From the controller:
public ActionResult Create(int custId, int projId)
{
return View();
}
From the view:
#Html.ActionLink("Back to List", "Index", "Conflict", new { custId = ViewBag.custId, projId = ViewBag.projId }, null)
The resulting link that gets created.
http://localhost:1283/Conflict?custId=1200&projId=300
If I change the controller code to read as follows:
public ActionResult Create(int custId, int projId)
{
ViewBag.custId = custId;
ViewBag.projId = projId;
return View();
}
I didn't make any changes in the view, only added those two lines to the controller and the following link is created:
http://localhost:1283/Conflict/Index/1200/300
What am I missing here? This is consistent behavior, I was able to reproduce this in other areas of my application. The "solution" is obvious, but my question is why?
What's happening is the "?custId=1200&projId=300" part of your link is coming over from the link you used to GET the page you're on. So the Html.ActionLink call is doing this:
generate the /Conflict/Index path
look for the custId and projId in the ViewBag and finds the query string instead
just appends your query string
In the second scenario, you're actually providing values, so the link is generating normally. Hope that helps.

Resources