I've tried converting an MVC 2 tutorial webshop to MVC 3 with Razor Syntax, but I don't understand the following problem...
_Layout.cshtml
<div id="header">
<div class="title">SPORTS STORE</div>
</div>
<div id ="categories">
#{Html.RenderAction("Menu", "Nav");}
</div>
"Menu" is an action for a partial View on the "Nav" Controller.
Menu.cshtml
#model IEnumerable<WebShop_1_0.ViewModels.NavLink>
#{foreach(var link in Model)
{
Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object>
{
{ "class", link.IsSelected ? "selected" : null }
});
}}
This is the Nav controller
public class NavController : Controller
{
private IProductsRepository productsRepository;
public NavController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult Menu(string category)
{
// Just so we don't have to write this code twice
Func<string, NavLink> makeLink = categoryName => new NavLink
{
Text = categoryName ?? "Home",
RouteValues = new RouteValueDictionary(new
{
controller = "Products",
action = "List",
category = categoryName,
page = 1
}),
IsSelected = (categoryName == category)
};
// Put a Home link at the top
List<NavLink> navLinks = new List<NavLink>();
navLinks.Add(makeLink(null));
// Add a link for each distinct category
//navLinks.AddRange(productsRepository.Products.Select(x => x.Category.Trim()).Distinct().OrderBy(x => x));
var categories = productsRepository.Products.Select(x => x.Category.Trim());
foreach (string categoryName in categories.Distinct().OrderBy(x => x))
navLinks.Add(makeLink(categoryName));
return View(navLinks);
}
}
I don't know where the mistake is.
If I use Html.PartialView instead of Html.RenderAction, I get another error message, that VS can't find the PartialView. Most of this is code that I have just copied, just the Views rewritten to MVC 3.
Before this StackOverFlowException problem, the browser would load the webpage for a long time.
This is the routing:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
/*Sorrend geccire számít*/
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(null, "", // Only matches the empty URL (i.e. ~/)
new
{
controller = "Products",
action = "List",
category = (string)null,
page = 1
}
);
routes.MapRoute(null, "Page{page}", // Matches ~/Page2, ~/Page123, but not ~/PageXYZ
new { controller = "Products", action = "List", category = (string)null },
new { page = #"\d+" } // Constraints: page must be numerical
);
routes.MapRoute(null, "{category}", // Matches ~/Football or ~/AnythingWithNoSlash
new { controller = "Products", action = "List", page = 1 }
);
routes.MapRoute(null, "{category}/Page{page}", // Matches ~/Football/Page567
new { controller = "Products", action = "List" }, // Defaults
new { page = #"\d+" } // Constraints: page must be numerical
);
routes.MapRoute(null, "{controller}/{action}");
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactroy());
ModelBinders.Binders.Add(typeof(Cart), new CartModelBlinder());
}
}
Your Menu action needs to return a PartialView(navLinks) instead of View(navLinks), otherwise your layout will be drawn with the menu, which causes recursion. Oh oh! This causes the stack overflow :)
Related
I'm trying to create a generic route to work with slugs, but I always got an error
The idea is, instead of www.site.com/controller/action I get in the url a friendly www.site.com/{slug}
e.g. www.site.com/Home/Open would be instead www.site.com/open-your-company
Error
server error in '/' application The Resource cannot be found
In my Global.asax I have
public static void RegisterRoutes(RouteCollection routes)
{
//routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("DefaultSlug", "{slug}", new { controller = "Home", action = "Open", slug = "" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
slug = ""
}
);
}
In one of my cshtml I have the following link (even when it's commented, there is still the same error).
#Html.ActionLink("Open your company", "DefaultSlug", new { controller = "Home", action = "Open", slug = "open-your-company" })
EDIT: HomeController
public ActionResult Open() {
return View(new HomeModel());
}
In Global.asax you slug can not be empty,if empty ,the url will be not go to the default route
public static void RegisterRoutes(RouteCollection routes)
{
//routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultSlug",
url: "{slug}",
defaults: new { controller = "Home", action = "Open" },
constraints: new{ slug=".+"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
And update the HomeController
public ActionResult Open(string slug) {
HomeModel model = contentRepository.GetBySlug(slug);
return View(model);
}
Testing Route link...
#Html.RouteLink("Open your company", routeName: "DefaultSlug", routeValues: new { controller = "Home", action = "Open", slug = "open-your-company" })
and Action link...
#Html.ActionLink("Open your company", "Open", routeValues: new { controller = "Home", action = "Open", slug = "open-your-company" })
both produces...
http://localhost:35979/open-your-company
Here's the steps I took to accomplish a similar task. This relies on a custom Slug field on the model to match against the route.
Set up your controller e.g. Controllers\PagesController.cs:
public class PagesController : Controller
{
// Regular ID-based routing
[Route("pages/{id}")]
public ActionResult Detail(int? id)
{
if(id == null)
{
return new HttpNotFoundResult();
}
var model = myContext.Pages.Single(x => x.Id == id);
if(model == null)
{
return new HttpNotFoundResult();
}
ViewBag.Title = model.Title;
return View(model);
}
// Slug-based routing - reuse View from above controller.
public ActionResult DetailSlug (string slug)
{
var model = MyDbContext.Pages.SingleOrDefault(x => x.Slug == slug);
if(model == null)
{
return new HttpNotFoundResult();
}
ViewBag.Title = model.Title;
return View("Detail", model);
}
}
Set up routing in App_Start\RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
// Existing route register code
// Custom route - top priority
routes.MapRoute(
name: "PageSlug",
url: "{slug}",
defaults: new { controller = "Pages", action = "DetailSlug" },
constraints: new {
slug = ".+", // Passthru for no slug (goes to home page)
slugMatch = new PageSlugMatch() // Custom constraint
}
);
}
// Default MVC route setup & other custom routes
}
}
Custom IRouteConstraint implementation e.g. Utils\RouteConstraints.cs
public class PageSlugMatch : IRouteConstraint
{
private readonly MyDbContext MyDbContext = new MyDbContext();
public bool Match(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
var routeSlug = values.ContainsKey("slug") ? (string)values["slug"] : "";
bool slugMatch = false;
if (!string.IsNullOrEmpty(routeSlug))
{
slugMatch = MyDbContext.Pages.Where(x => x.Slug == routeSlug).Any();
}
return slugMatch;
}
}
In my project there is an action
public ActionResult Lead(int leadId)
{
return View();
}
and in the View an ActionLink was created like this
#Html.ActionLink("Old Link", "Lead", "Home", new { leadId = 7 }, null)
But after some time, to make clean URL, I have changed the name of parameter of that action
public ActionResult Lead(int id)
{
return View();
}
And ActionLink change accordingly
#Html.ActionLink("New Link", "Lead", "Home", new { id = 5 }, null)
But old link was shared in multiple social network sites. Whenever anyone clicks on that old link, he is redirect to the page www.xyx.com/Home/Lead?leadId=7
But now in my application, no such URL exists.
To handle this problem, I was thinking of overloading, but MVC action doesn't support overloading.
I have created another Action with same name with extra parameter, and redirect to new action, but it doesn't work.
public ActionResult Lead(int leadId, int extra=0)
{
return RedirectToAction("Lead", "Home", new { id = leadId });
}
I have found one link to handle such situation, but It is not working in my case.
ASP.NET MVC ambiguous action methods
One possibility to handle this would be to write a custom route:
public class MyRoute : Route
{
public MyRoute() : base(
"Home/Lead/{id}",
new RouteValueDictionary(new
{
controller = "Home",
action = "Lead",
id = UrlParameter.Optional,
}),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var leadId = httpContext.Request.QueryString["leadid"];
if (!string.IsNullOrEmpty(leadId))
{
rd.Values["id"] = leadId;
}
return rd;
}
}
that you will register before the default one:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new MyRoute());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
and now you could only have a single action:
public ActionResult Lead(int id)
{
return View();
}
Now both the following urls will work as expected:
www.xyx.com/Home/Lead/7
www.xyx.com/Home/Lead?leadId=7
As the title says all about what I want but to be kind of specific I would like to have a URL pattern like localhost/Product/List/Category/Page but I couldn't succeed finding a solution for it. I am sure it's belong to routing and as it is difficult topic in MVC I would need your help to find a solution for it.
My route config is:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(null, "",
new
{
controller = "Home",
action = "Shop",
});
routes.MapRoute(null, "",
new
{
controller = "Product",
action = "list",
category = (string)null,
page = 1
}
);
routes.MapRoute(null, "Page{page}",
new
{
controller = "Product",
action = "List",
category = (string)null,
subcategory = (string)null
},
new { page = #"\d+" }
);
routes.MapRoute(null,
"{category}",
new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(null,
"{category}/Page{page}",
new { controller = "Product", action = "List" },
new { page = #"\d+" }
);
routes.MapRoute(null, "{controller}/{action}");
}
}
My Controller product is:
public class ProductController : Controller
{
EFDbContext db = new EFDbContext();
private IProductsRepository repository;
public int PageSize = 4;
public ProductController (IProductsRepository productrepository)
{
this.repository = productrepository;
}
public ViewResult List(string category, int page = 1)
{
ProductsListViewModel model = new ProductsListViewModel()
{
Products = repository.Products
.Where(p => category == null || p.ProductCategory == category || p.MenSubCategory == category)
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = category == null ? repository.Products.Count():repository.Products.Where(e => e.ProductCategory == category).Count()
},
CurrentCategory = category
};
return View(model);
}
public PartialViewResult Menu(string subcategory = null )
{
ViewBag.SelectedCategory = subcategory;
IEnumerable<string> categories = repository.MenSubCategories
.Select(x => x.MenSubCategory)
.Distinct()
.OrderBy(x => x);
return PartialView(categories);
}
}
I hope I get answer for this as far as I really tried but couldn't find how to do it.
To generate an URL like you want: localhost/Product/List/Cars you can create a custom route like this:
routes.MapRoute(
name: "ProductList",
url: "Product/List/{category}",
defaults: new { controller = "Product", action = "List" }
);
Remember that custom routes have to come before the most general route (the one that comes with the default template).
Regarding your page parameter, if you are comfortable with this URL: localhost:3288/Product/List/teste?page=10 the above already work. But if you want this: localhost:3288/Product/List/teste/10 10 meaning the page number, then the simplest solution would be create two different routes:
routes.MapRoute(
name: "ProductList",
url: "Product/List/{category}",
defaults: new { controller = "Product", action = "List" }
);
routes.MapRoute(
name: "ProductListPage",
url: "Product/List/{category}/{page}",
defaults: new { controller = "Product", action = "List" , page = UrlParameter.Optional}
);
Another cleaner way, is to create a custom route constraint for your optional parameter. This question has a lot of answers to that:
ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+
With attribute routing, you just need to decorate your action method with your specific route pattern.
public class ProductController : Controller
{
EFDbContext db = new EFDbContext();
private IProductsRepository repository;
public int PageSize = 4;
public ProductController (IProductsRepository productrepository)
{
this.repository = productrepository;
}
[Route("Product/list/{category}/{page}")]
public ViewResult List(string category, int page = 1)
{
// to do : Return something
}
}
The above route definition will send the request like yourSite/Product/list/phones and yourSite/Product/list/phones/1 to the List action method and the url segments for category and page will be mapped to the method parameters.
To enable attribute routing, you need to call the method MapMvcAttributeRoutes
method inside the RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I am new to programming with C# and MVC4 the error happens at
#{
Html.RenderAction("Menu", "Nav");
}
It is coming back with an error stating that there is no route in the route table matches the supplied values. I have tried searching the internet to no avail, any help would be greatly appreciated. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<link href="~/Content/Site.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="header">
<div class="title">Bag Labels</div>
</div>
<div id="categories">
#{ Html.RenderAction("Menu", "Nav"); }
</div>
<div id="content">
#RenderBody()
</div>
</body>
</html>
This is the _Layout.cshtml
Here is my NavController.cs
using NavisionStore.Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NavisionStore.WebUI.Controllers
{
public class NavController : Controller
{
private IProductRepository repository;
public NavController(IProductRepository repo)
{
repository = repo;
}
public PartialViewResult Menu(string category = null)
{
ViewBag.SelectedCategory = category;
IEnumerable<string> categories = repository.Products
.Select(x => x.Category)
.Distinct()
.OrderBy(x => x);
return PartialView(categories);
}
}
}
Here is my RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace NavisionStore.WebUI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(null,
"",
new {
controller = "Product", action = "List",
category = (string)null, page = 1
}
);
routes.MapRoute(null,
"Page{page}",
new { controller = "Product", action = "List", category = (string)null },
new { page = #"\d+" }
);
routes.MapRoute(null,
"{category}",
new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(null,
"{category}/Page{page}",
new { controller = "Product", action = "List" },
new { page = #"\d+" }
);
routes.MapRoute(null, "{contoller}/{action}");
}
}
}
Here is my ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NavisionStore.Domain.Abstract;
using NavisionStore.Domain.Entities;
using NavisionStore.WebUI.Models;
namespace NavisionStore.WebUI.Controllers
{
public class ProductController : Controller
{
private IProductRepository repository;
public int PageSize = 1;
public ProductController(IProductRepository productRepository)
{
this.repository = productRepository;
}
public ViewResult List(string category, int page = 1)
{
ProductsListViewModel ViewModel = new ProductsListViewModel
{
Products = repository.Products
.Where(p => category == null || p.Category == category)
.OrderBy(p => p.Id)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
},
CurrentCategory = category
};
return View(ViewModel);
}
}
}
Remove the following routes from your routing config:
routes.MapRoute(null,
"",
new {
controller = "Product", action = "List",
category = (string)null, page = 1
}
);
routes.MapRoute(null, "{contoller}/{action}");
Also, the following routes are likely not doing what you are expecting, as each one is actually returning the same controller/action for each matching url. I recommend removing them.
routes.MapRoute(null,
"Page{page}",
new { controller = "Product", action = "List", category = (string)null },
new { page = #"\d+" }
);
routes.MapRoute(null,
"{category}",
new { controller = "Product", action = "List", page = 1 }
);
routes.MapRoute(null,
"{category}/Page{page}",
new { controller = "Product", action = "List" },
new { page = #"\d+" }
);
They could be replaced with the following:
routes.MapRoute(
"Page",
"Product/List/{category}/{page}",
new { controller = "Product", action = "List", page = UrlParameter.Optional },
new { page = #"\d*" }
);
Finally, add names to all of your routes, not null. Currently, the only one you have named is "default".
In the end, you should be at a much simpler routing configuration for what you are trying to do:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// matches:
// product/list/unicorns
// product/list/carrots/15
routes.MapRoute(
"Page",
"Product/List/{category}/{page}",
new { controller = "Product", action = "List", page = UrlParameter.Optional },
new { page = #"\d*" } //<-- note the asterisk here
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Product", action = "List",
id = UrlParameter.Optional
}
You are using
Html.RenderAction
so rather try
public ActionResult Menu(string category = null)
{
// Your controller code.
return View(categories);
}
instead of
public PartialViewResult Menu(string category = null)
{
// Your controller code.
return PartialView(categories);
}
it also looks like you are missing your default route mapping
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "[Your default controller name goes here]",
action = "[Your default action name goes here]", id = UrlParameter.Optional}
);
Update
I don't know if all those routing rules that is specified in your RouteConfig.cs file is needed. Keep it as simple as possible, for example
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login",
action = "Index", id = UrlParameter.Optional }
);
}
Update
Your Menu action is expecting a category parameter, so you will have to pass it one, or setup a proper route mapping. So change
#{
Html.RenderAction("Menu", "Nav");
}
to
#{
Html.RenderAction("Menu", "Nav", new {category = null});
}
Charlie Brown has resolved a stupid error on my part. I misspelled "controller" on the last route as "controller". I feel like and idiot, I have missed this spelling error for a month now. Thanks for your help I appreciate it.
If you just need a piece of HTML on every page you can use partial view like this:
#Html.Patial("_Menu")
instead of
#{ Html.RenderAction("Menu", "Nav"); }
Here _Menu is name of partial view _Menu.cshtml (should be placed in Views/Shared)
UPDATE 1
If you need pass some object (lets say collection) to the partial view just specify it as second parameter:
#Html.Patial("_Menu", collection)
collection object will be your model in _Menu.cshtml view, so you can use it as usual:
#model System.Collections.Generic.IEnumerable<string>
<select>
#foreach(var item in Model)
{
<option>#item</option>
}
</select>
UPDATE 2
Also your routes rules are too weird. Why don't you use default routing only:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
This will allow you to call your action like this:
.../nav/menu
.../product/list
.../ which will equals to .../product/list since default controller was set to ProductController and default action was set to List method.
Any way in route rule you always have to specify unique name and template. But you are passing empty string as rule name - it's wrong. You should replace whole your RouteConfig.cs as #user65439 mentioned in his answer.
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.