I have a controller action method that needs to be able to serve multiple views. These views are generated by XSLT.
Now, the views have images in them (hundreds each), and each view needs to have its own folder with images to refer to. How should this work?
If the images in the source XML has an href that is a simple relative path ("images/image.svg"), how can I get this path to resolve in the view in the application?
If I could put the images folder in the same folder as the view, and use a relative path there, it would be easy, but that doesn't work, because I'm serving multiple views from the action. Here is the routing:
routes.MapRoute(
"Parameter",
"{controller}/{action}/{lang}/{prod}",
new { controller = "Manuals", action = "Product", lang = "en-US", prod = "sample" }
);
So if I try using a relative path for the img src attribute, it resolves to something like "/Manuals/Product/en-US/images/image.svg"
And in fact, if I put it relative to the view, the image is located in "/Views/Manuals/en-US/images/image.svg"
So is there no way to have relative image paths like this in Asp.Net MVC? Or am I misunderstanding MVC routing completely?
This is what I have done before:
public class MvcApplication : HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
MapRoute(routes, "", "Home", "Index");
/* other routes */
MapRoute(routes, "{*url}", "Documentation", "Render");
}
}
Now any routes that are not matched are passed to the DocumentationController. My documentation controller looks as follows:
public class DocumentationController : Controller
{
public ActionResult Render(string url)
{
var md = new MarkdownSharp.Markdown();
// The path is relative to the root of the application, but it can be anything
// stored on a different drive.
string path = Path.Combine(Request.MapPath("~/"), GetAppRelativePath().Replace('/', '\\')) + ".md";
if (System.IO.File.Exists(path))
{
string html = md.Transform(System.IO.File.ReadAllText(path));
return View("Render", (object)html);
}
// return the not found view if the file doesn't exist
return View("NotFound");
}
private string GetAppRelativePath()
{
return HttpContext.Request.AppRelativeCurrentExecutionFilePath.Replace("~/", "");
}
}
All this does is to find markdown files and render them accordingly. To update this for your case, you may want to do the following:
routes.MapRoute(
"Parameter1",
"{controller}/{action}/{lang}/{*url}",
new { controller = "Manuals", action = "Download", lang = "en-US", prod = "sample" }
);
Make sure it is after the {controller}/{action}/{lang}/{prod} route. This should cause a URL such as /Manuals/Product/en-US/images/image.svg or even images/image.svg (if the browser is in /Manuals/Product/en-US/sample to invoke the the Download action. You can then adapt the code I wrote to map that URI to the physical location. A problem you may run into is that "images" are considered to be product and that /Manuals/Product/en-US/images would think its a product.
The Images action can be can look as follows.
public ActionResult Download(string url)
{
/* figure out physical path */
var filename = /* get filename form url */
var fileStream = [...];
Response.Headers.Remove("Content-Disposition");
Response.Headers.Add("Content-Disposition", "inline; filename=" + filename);
string contentType = "image/jpg";
return File(fileStream, contentType, filename);
}
You can get more information of the FileResult at MSDN.
Related
I recently asked a question based on how to create pages based on the content table which contains the following: Title and Content. I followed the steps, to my understanding, in the answer that was given.
I created a route like so:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"ContentManagement",
"{title}",
new { controller = "ContentManagement", action = "Index", title = "{title}" }
);
}
I am assuming I can do routes like this? where I can set up multiple routes? I am also assuming I can pass the title to to the controller action like I have done?
I then created the model:
namespace LocApp.Models
{
public class ContentManagement
{
public int id { get; set; }
[Required]
public string title { get; set; }
public string content { get; set; }
}
}
from that I created a controller with an index action that looks as such:
public ViewResult Index(string title)
{
using (var db = new LocAppContext())
{
var content = (from c in db.Contents
where c.title == title
select c).ToList();
return View(content);
}
}
So then I created some content with the title of "bla" so when I visit site.com/bla I get an error that it cant find "bla/"
Can some one tell me what I am doing wrong? I would also, if you are familiar with the default layout of a asp.net mvc project with the tabs at the top, create a set of tabs that lead to the pages, based on the title in the database
The main issue is that when you are using the title, the routing engine is matching it to the first route and trying to find a controller by that title. We have implemented something similar and found that by explicitly defining what controllers are valid for the default route, it then processed request appropriately. I gave an example of the controllers that we allow to fit our default route below (Home, Help and Error).
You probably also want to prevent people from giving the content the same TITLE as your root level controllers as that would blow this up pretty well.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional},
new {controller = "Home|Error|Help"},
new[] {"UI_WWW.Controllers"});
routes.MapRoute(
"ContentManagement",
"{title}",
new {controller = "ContentManagement", action = "Index"});
}
}
I followed this tutorial, and created this code:
using Glass.Sitecore.Mapper;
using Sitecore.Mvc.Controllers;
using Sitecore.SecurityModel;
using SitecoreCMSMVCBase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SitecoreCMSMVCBase.Controllers
{
public class CommentController : SitecoreController
{
ISitecoreContext _context;
ISitecoreService _master;
public CommentController()
: this(
new SitecoreContext(),
new SitecoreService("master"))
{
}
/// <summary>
/// This constructor can be used with dependency injection or unit testing
/// </summary>
public CommentController(ISitecoreContext context, ISitecoreService master)
{
_context = context;
_master = master;
}
[HttpGet]
public override ActionResult Index()
{
var model = _context.GetCurrentItem<CommentPage>();
return View(model);
}
[HttpPost]
public ActionResult Index(Comment comment)
{
var webModel = _context.GetCurrentItem<CommentPage>();
if (ModelState.IsValid)
{
var masterModel = _master.GetItem<CommentPage>(webModel.Id);
if (masterModel.CommentFolder == null)
{
CommentFolder folder = new CommentFolder();
folder.Name = "Comments";
using (new SecurityDisabler())
{
_context.Create(masterModel, folder);
}
masterModel.CommentFolder = folder;
}
using (new SecurityDisabler())
{
comment.Name = DateTime.Now.ToString("yyyyMMddhhmmss");
//create the comment in the master database
_master.Create(masterModel.CommentFolder, comment);
webModel.CommentAdded = true;
}
}
return View(webModel);
}
}
}
Models are identical with tutorial, so I will not paste them.
My route configuration looks like this:
routes.MapRoute(
"CommentController", // Route name
"Comment/{action}/{id}", // URL with parameters
new { controller = "Comment", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
When I navigate to /comment I see this exception:
Glass.Sitecore.Mapper.MapperException: Context has not been loaded
I tried with commenting my route specification (as there was nothing about routes in tutorial), and then error is different (throwing by Sitecore CMS itself):
The requested document was not found
Do you know how to load Sitecore context into custom Controller, and make this simple example work? I was looking everywhere but couldn't find any good answer...
I think this is more a Glass setup issue, rather than an MVC routing problem.
To setup Glass, you need to initialise the context in your application start method in your Global.asax file.
var loader = new Glass.Sitecore.Mapper.Configuration.Attributes.AttributeConfigurationLoader(
"Glass.Sitecore.Mapper.Tutorial.Models, Glass.Sitecore.Mapper.Tutorial");
Glass.Sitecore.Mapper.Context context = new Context(loader);
For other Glass-setup related stuff I recommend following the first tutorial on the glass.lu website.
http://www.glass.lu/tutorials/glass-sitecore-mapper-tutorials/tutorial-1-setup/
This method doesn't need Glass at all!
First step is to set your route in Global.asax file.
routes.MapRoute(
"DemoController", // Route name
"Demo/{action}/{param}", // URL with parameters
new { controller = "Demo", action = "Index", param = "", scItemPath = "/sitecore/content/DemoHomePage" } // Parameter defaults
);
Notice that controller is not taken as parameter, but is fixed, to prevent handling it by Sitecore. More info here and here. Notice that there is one additional parameter - scItemPath. It contains path to item which by default will be included in page context.
Having this route our traffic from /demo is handled by DemoController and Index action. Inside this action all you need is to add is this line:
Sitecore.Data.Items.Item item = Sitecore.Mvc.Presentation.PageContext.Current.Item;
item variable will contain your Sitecore item pointed by scItemPath.
And that's all - it should work well now - hope it helps!
new to asp.net mvc (using v3 + razor) and am wondering how to best solve a problem with creating dynamic routes based on a database. Essentially, the main site navigation will be entered into a database and I want to load them up as routes. i.e. - Load Category list from database, then append the routes to the routing engine if possible...
mysite.com/cars
mysite.com/televisions
mysite.com/computers
etc....
Each category after the slash comes from the db, but, there are regular entries like /about and /contactus that will not be in the database and have been statically entered in the global.asax... my question is:
For the dynamic database URLs should I use a custom RouteHandler or pehaps create a ControllerFactory that will match and handle the requests for the entries loaded from the database. Is it possible to have the DefaultControllerFactory handle the routing if my RouteHandler or CustomControllerFactory don't find the route in the list from the database? Thanks for any help, very first project with this so I'm not sure what the best route is ;) no pun intended...
Update:
Tried using a route constraint that pulls from the database but it conflicts with the default route now... here is my custom constraint and routes:
public class CategoryListConstraint : IRouteConstraint
{
public CategoryListConstraint()
{
var repo = new Repository<Topic>();
var cats = repo.All();
var values = new List<string>();
foreach (var c in cats)
{
values.Add(c.URI.Replace("/", "").Replace("?", ""));
}
this._values = values.ToArray<string>();
}
private string[] _values;
public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"
string value = values[parameterName].ToString();
// Return true is the list of allowed values contains
// this value.
return _values.Contains(value);
}
}
and here are the routes:
Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Categories",
"{category}/{*values}",
new { controller = "Category", action = "List" },
new CategoryListConstraint()
);
Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
The home page www.mysite.com loads using the Default route. All the URLs that match the constraint list are loaded by the category route... but if I have the www.mysite.com/admin or www.mysite.com/aboutus these are getting picked up by the Categories route even though the values are not in the constraint list. Confused...
What about something like this?
Categories controller:
public ActionResult List(string category)
{
var products = _repo.Get(category); // however you are getting your data
return View(products);
}
Routes
routers.MapRoute(
"About",
"About",
new { controller = "Home", action = "About" });
//... other static routes
routes.MapRoute(
"CategoriesList",
"{id}",
new { controller = "Categories", action = "List" },
new { id = #"\w+" });
The incoming URL is tested against each Route rule to see if it matches - and if a Route rule matches then that rule (and its associated RouteHandler) is the one that is used to process the request (and all subsequent rules are ignored). This means that you want to typically structure your routing Rules in a "most specific to least specific" order
source
Found the exact solution I was looking for. Code is below. I managed to avoid using Controller Factories or implementing a custom IRouteHandler by using extending the RouteBase class which worked perfectly and allows me to pass control down to the default mvc route is something specific isn't hit. BTW - constraints ended up not working properly as the broke the controllers associated with the default route (although the default route was getting hit)
public class CustomRoutingEngine : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var routeHandler = new MvcRouteHandler();
var currentRoute = new Route("{controller}/{*URI}", routeHandler);
var routeData = new RouteData(currentRoute, routeHandler);
// implement caching here
var list = GetConstraintList();
// set your values dynamically here
routeData.Values["controller"] = "Category";
// or
routeData.Values.Add("action", "List");
// return the route, or null to have it passed to the next routing engine in the list
var url = Util.StripSlashOnFrontAndBack(httpContext.Request.Path.ToLower()).Split('/')[0];
if (list.Contains(url))
return routeData;
return null; // have another route handle the routing
}
protected List<string> GetConstraintList()
{
using (var repo = new RavenRepository<Topic>())
{
var tops = repo.Query().Where(x => x.Hidden == false).ToList()
.Select(x=>x.Name.ToLower());
List<string> list = new List<string>();
list.AddRange(tops);
repo.Dispose();
return list ?? new List<string>();
}
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
//implement this to return url's for routes, or null to just pass it on
return null;
}
}
Then my register routes method looks like so:
Routes.Clear();
// Set Defaults
Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.Add(new App.Helpers.CustomRoutingEngine());
Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
I am trying to implement a custom view engine with Razor. The goal is if the view is in a sub folder to use that view instead.
I have my view engine derived from the RazorViewEngine
public class RazorViewFactory : RazorViewEngine
{
public RazorViewFactory()
{
string TenantID = ConfigurationManager.AppSettings["TenantID"];
if (TenantID != null)
{
MasterLocationFormats = new[] {
"~/Views/Shared/{0}.cshtml"
};
ViewLocationFormats = new[]{
"~/Tenant/" + TenantID + "/Views/{1}/{0}.cshtml",
"~/Tenant/" + TenantID + "/Views/Shared/{0}.cshtml",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml"
};
PartialViewLocationFormats = new[] {
"~/Tenant/" + TenantID + "/Views/{1}/{0}.cshtml",
"~/Tenant/" + TenantID + "/Views/Shared/{0}.cshtml"
};
}
}
}
and in my Global.asax
protected void Application_Start()
{
...
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewFactory());
}
Everything works except when I load my Tenant sub view Home page, I get the following error.
The view at '~/Tenant/TenantB/Views/Home/Index.cshtml'
must derive from WebViewPage, or WebViewPage<TModel>.
If I load the base home page it works fine with the Razor engine.
You need to copy the web.config file from your Views folder into your Tenant folder (or make sure it has the same config sections as described here: Razor HtmlHelper Extensions (or other namespaces for views) Not Found)
Anyone got the areaDescriptorFilter working with the spark view engine in asp.net mvc 2?
I don't even have the option to add a filter on the service as shown in the following:
http://sparkviewengine.com/documentation/viewlocations#Extendingfilepatternswithdescriptorfilters
Thanks if you can help or at least try.
I'm using areas with Spark in a project of mine. All I had to do was add AreaRegistration classes for each area like:
public class AdminAreaRegistration : System.Web.Mvc.AreaRegistration
{
public override string AreaName
{
get { return "Admin"; }
}
public override void RegisterArea( AreaRegistrationContext context )
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
and then in the global.asax call:
AreaRegistration.RegisterAllAreas();
I have my area views located in a folder named "Admin" under the default "Views" folder, with appropriate controller folders under that:
\MvcProject
\Views
\Admin
\Home
\Index.spark
\Users
\Index.spark
from the page you linked:
the AreaDescriptorFilter is added by default
so you shouldn't need to worry about adding it yourself.