I have an controller that takes 3 paramteres
public ActionResult Directives(string MachineName, int ProjectId, int CompanyId)
Right now the Url looks like this.
/Project/Directives?projectId=41&MachineName=Apple%20Macbook%20Luft
But how do i get it to look like this.
/Project/Directives/41/AppleMacbookAir/
Try a custom route:
routes.MapRoute(
"Project", // Route name
"{Controller}/{Action}/{projectId}/{machineName}/{companyId}",
new { controller = "Project", action = "Directives", projectId = 0, machineName = "", companyId = 0 } // Parameter defaults
);
http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs
You can pass the id as part of the routeValues parameter of the RedirectToAction() method.
return RedirectToAction("Action", new { id = 99 });
This will cause a redirect to Site/Controller/Action/99.
Edit:
For customizing url, you have to create custom route as:
routes.MapRoute( "Project", // Route name
"{controller}/{Action}/{ProjectId}/{MachineName}/{CompanyId}",
new { controller = "Project",
action = "Directives",
ProjectId= 0,
MachineName= "",
CompanyId = 0
} // Parameter defaults );
Use UrlParameter.Optional if you want any parameter optional.
Follow By Stephen Walthe article on ASP.NET MVC Routing
Refer this: RedirectToAction with parameter
Related
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())
},
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
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).
I have a route like this:
http://localhost/c/61/legetoj
its defined as:
routes.MapLocalizedRoute("Category",
"c/{categoryId}/{SeName}",
new { controller = "Catalog", action = "Category", SeName = UrlParameter.Optional },
new { categoryId = #"\d+" },
new[] { "Nop.Web.Controllers" });
Now, on all the pages having this url, I want to get SeName value (here is `legetoj')
In my view (header) I've tried this with: ViewContext.RouteData.Values["SeName"]
but it returns empty..
Do you know what I am doing wrong?
Just set up an action with the same name parameter as you would like to accept such as:
public ActionResult Category(int categoryId, string SeName) {
// do stuff
}
It should automatically insert that value inside the variable.
I would like to receive a string as the id in the URL. Here is an example:
http://www.example.com/Home/Portal/Fishing
I would like to have Fishing in my id. But I cannot achieve it with the following code:
Code from my Controller:
public ActionResult Portal(string name)
{
// some code
ViewData["Portal Name"] = name;
}
Code from Global.asax.cs:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Just change the argument to id:
public ActionResult Portal(string id)
{
// some code
ViewData["Portal Name"] = id;
}
The argument will be bound if it has the same name as the route value token. So an alternate approach would be to keep the argument named name and change the route:
public ActionResult Portal(string name)
{
// some code
ViewData["Portal Name"] = name;
}
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{name}", // URL with parameters
new { controller = "Home", action = "Index", name = UrlParameter.Optional } // Parameter defaults
);
I would choose using id, though, as it's the more standard approach.