For example, I need only documents from a folder on the server drive X:\Docs for an online web application. Is there a way that a button on the website will open X:\Docs by default? I have tried this to open specific folders with no luck:
[HttpPost]
public ActionResult Index(HttpFileCollection file)
{
var path = System.IO.Path.GetDirectoryName("X:\Docs");
return RedirectToAction("Index");
}
I am new to C# and MVC. Is this achievable?
You can enable directory browsing of that folder and then having the button (or href) to point to the url. You don't event need a controller method for it.
Updated: if the folder is not under your website's root you will need to do some work by yourself. For example
#foreach (string path in Directory.GetFiles("X:\Docs"))
{
<div>
<!--doc link-->
</div>
}
You will need to have read permission for that drive ofc
As Luke pointed out you could alo do this inside your controller and pass it into your View which I also think it might be a better approach since View should be responsible for reading and rendering data
I have a website that use this pattern.
http://www.domain.com/product/...
My question is now, i need to create a subsite that going to be with this URL pattern, i have tried to change the routing without success.
http://www.domain.com/companyname/product/...
How can i inject the companyname in the URL without breaking my current routing?
Thanks
Niden
Three ways:
If it's relatively static, you can follow Andy's advice in the comments and publish the site in a virtual directory, companyname. Assuming you've properly used the UrlHelper extensions to generate URLs, instead of just hard-coding paths, then everything will just work.
You can create a "companyname" area. The default routing for an area is /area/controller/action. So that would get you the URL structure you want. However, areas are somewhat segregated, so you would need to copy controllers and views to the area's directory. Although, you could subclass controllers from the main app in the area to reuse code.
Just change the default route/add a new route:
routes.MapRoute(
"CompanyDefault",
"{company}/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
// default route here
Can we add dynamically routes to global.asax file
Suppose if I have multiple routes for the same page for example
http://website.com/about
http://website.com/en/about
http://website.com/en/about-us
While my actual URL for the page is like http://website.com/en/about-us.
My question now is: is there a way I can dynamically define these routes in global.asax file in such a way that it reads the URL entered by users like http://website.com/about and then compares it with database table and redirects it to the correct page which is http://website.com/en/about-us?
Taking into consideration following Table Structure:
Id URL_Name URL Actual_URL Page_Handler
1 Home http://website.com/ http://website.com/ Default.aspx
2 About Us http://website.com/about http://website.com/en/about-us About.aspx
3 About Us http://website.com/about-us http://website.com/en/about-us About.aspx
4 About Us http://website.com/en/about http://website.com/en/about-us About.aspx
5 Contact http://website.com/contact http://website.com/en/contact-us Contact.aspx
6 Contact http://website.com/en/contact http://website.com/en/contact-us Contact.aspx
Right now I have to configure each route manually in the global.asax:
if(HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://website.com/about")
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.Redirect("http://website.com/en/about-us");
}
if(HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://website.com/en/about")
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.Redirect("http://website.com/en/about-us");
}
A pointer to a good example or a solution is highly appreciated.
I find routes in global.asax are great for static resources especially if you want a nice, sexy extensionless URLs for SEO.
For dynamic pages/URLs though, I tend to have a catch all route that handles the request if it doesn't match any static routes.
eg
// ignore
routes.Add(new System.Web.Routing.Route("{resource}.axd/{*pathInfo}", new System.Web.Routing.StopRoutingHandler()));
// sexy static routes
routes.MapPageRoute("some-page", "some-sexy-url", "~/some/rubbish/path/page.aspx", true);
// catch all route
routes.MapPageRoute(
"All Pages",
"{*RequestedPage}",
"~/AssemblerPage.aspx",
true,
new System.Web.Routing.RouteValueDictionary { { "RequestedPage", "home" } }
);
So, when a request comes in it checks each static route in turn and executes the specified page. If no match is found, it drops through to the catch all and then AssemblerPage.aspx handles the request. This AssemblerPage will analyse the requested URL and redirect, rewrite path or stick some controls on the page to render - basically, it can do whatever you want it to do.
In your case, I'd have the AssemblerPage check the DB and compare the requested URL with the URLs in your table. Then simply redirect or rewrite path.
Would ASP.NET Routing help you here ?
Have a look at this: - ASP.net URL rewrite based off query string ID
This app has several routes configured in RouteConfig.cs. For instance, I have the two following routes defined:
routes.MapRoute(
name: "MyPage-Demo",
url: "pages/page-title/demo",
defaults: new { controller = "Root", action = "PageDemo" }
);
routes.MapRoute(
name: "MyPage",
url: "pages/page-title/{resource}",
defaults: new { controller = "Root", action = "Page", resource = UrlParameter.Optional }
);
Each page someone visits has a link to a "demo". A page could be accessed by visiting http://localhost/pages/page-title. This works fine.
When a user clicks the "demo" link, they are redirected to a page located at http://localhost/pages/page-title/demo. This works fine.
My problem is the demo page may reference a complex nested structure. The structure consists of JavaScript, css, images, etc. Content used for the purpose of the demo. None of these nested resources can be found. However, I'm not sure how to setup my routing to account for these nested files.
I'm confident I'm going to need to update my controller's PageDemo action. However, I'm not sure
a) how to do so in a way that will allow for differing structures and
b) how to update my route configuration to account for these nested structures.
Is there a way to do this? In reality, I'm going to have multiple pages and multiple demos. For that reason, I want to have something a little more reusable than a hard-coded approach.
If you just need to serve files physically stored in a path, you should be able to just ignore the route, e.g.:
routes.IgnoreRoute("pages/page-title/demo/resources/{*resource}");
That will bypass MVC trying to route the request to a controller.
Or you could go by file extension:
routes.IgnoreRoute("{file}.js");
routes.IgnoreRoute("{file}.css");
(Code is untested, but it looks like you're trying to do something similar here :)
https://stackoverflow.com/a/3112192/486620
IF I understand:
The problem seems to be that your MyPage-Demo route:
routes.MapRoute(
name: "MyPage-Demo",
url: "pages/page-title/demo",
defaults: new { controller = "Root", action = "PageDemo" }
);
is NOT {resource} specific, while your MyPage route IS.
If you change your route to take a {resource}
routes.MapRoute(
name: "MyPage-Demo",
url: "pages/page-title/demo/{resource}",
defaults: new { controller = "Root",
action = "PageDemo", resource = UrlParameter.Optional });
Then your action method can
return specific Views with proper resource settings
set a Viewbag property with path to your specific resource
If this is inline with your intent, these routes can be consolidated into
routes.MapRoute(
name: "MyPage-Demo",
url: "pages/{action}/{resource}",
defaults: new { controller = "Root",
action = "PageDemo", resource = UrlParameter.Optional });
/pages/PageDemo/{resource} resolves to Controller=pages, action = PageDemo
/pages/demo/{resource} resolves to Controller=pages, action = demo.
This convention allows you flexibility to create more {resource} dependant links
In the Browser, Right Click Demo page => Choose View Page Source.
Here, you have the link for the CSS and Js files in your Demo page. Click on those js/css file links. Check if there are redirecting you to the correct/expected location. Otherwise you could make the Css/Js file URL accordingly Because, as per the demo page each PageDemo will have its own unique structure of JS/Images/css, etc
How are you referencing your JS and CSS files ?
If you use the tilde character like : ~/Content/Styles/Site.css you won't have any problem no matter where you are in your virtual path.
Also not 100% sure I am directly answering your question, but making the assumption that the resources you are trying to access are nested in a folder structure that mirrors the page structure - and the issue you are having is how to ignore the routes to these without having to know what they might be in advance?
This does a good job of explaining that: https://stackoverflow.com/a/30551/1803682
I would ask:
As #PKKG notes in his answer - do the links in the page source match what you expect?
How is this per-demo content served: e.g. by a service and not a static file?
this answer contains two approaches. the second one may be more suitable for your scenario. the first may be more suitable for a general mvc project
approach one
i suggest creating a organized structure in your content folder to store the scripts and css files, ie
/Content/Demos/Page-Title-1/
/Content/Demos/Page-Title-2/
/Content/Demos/Page-Title-3/
and
/Content/Demos/Common/
and then make a bundle to render the scripts and css files for each page title
ie.
bundles.Add(new StyleBundle("~/Demo/page-title/css").Include(
"~/Content/Demos/Page-Title-1/csscontent1.css",
"~/Content/Demos/Page-Title-1/csscontent2.css",
"~/Content/Demos/Page-Title-1/csscontent3.css",
"~/Content/Demos/Page-Title-1/csscontent4.css"));
bundles.Add(new StyleBundle("~/Demo/page-title/js").Include(
"~/Content/Demos/Page-Title-1/jscontent1.css",
"~/Content/Demos/Page-Title-1/jscontent2.css",
"~/Content/Demos/Page-Title-1/jscontent3.css",
"~/Content/Demos/Page-Title-1/jscontent4.css"));
this will allow you to render the scripts on the demo page using a few line approach, ie.
#Styles.Render("~/Demo/page-title/css");
#Scripts.Render("~/Demo/page-title/jss");
#Styles.Render("~/Demo/common/css");
#Scripts.Render("~/Demo/common/css");
you will have to update the files in global .asax as you change the files in your /Content/Demos/Page-Title/ folder.
there is the benefit that if you choose, you may bundle and minify the files to save bandwidth and load time for the first page load.
approach two.
(still use the following folder structure
/Content/Demos/Common/
and
/Content/Demos/Page-Title-1/
/Content/Demos/Page-Title-2/
/Content/Demos/Page-Title-3/)
make an html helper to reference all the scripts & contents in a folder
its usage would be
#Asset.RenderAssets( '~/folderdirectory')
and the helper would do something like
#helper RenderAssets (stirng directory){
#* scrape the directory for all script files*
var scripts = find all scripts in the directory
#* include the script files *#
for each script
<script src=" ... .js"></script>
#* scrape the directory for all cssfiles*
var styles = all css in the directory
#* include the css files *#
for each style
<link rel='stylesheet' type="text/css" href=" ... .css">
}
this would be a few line usage in each demo view
#Asset.RenderAssets( '~/Content/Demos/Common')
#Asset.RenderAssets( '~/Content/Demos/Page-Title')
you may or may not need to pair this with an extra few line or two in your global.asax or RouteConfig.cs file (see source 3)
routes.IgnoreRoute("/Content/Demos/{page}/{script}.js");
routes.IgnoreRoute("/Content/Demos/{page}/{style}.css");
relevant sources
to create html helpers see
http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx
to use bundling and minifcation (the scripts.render approach) see
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
phill haakk says may not need to pair this with an ignore route!
https://stackoverflow.com/a/30551/1778606
commentary and edits are encouraged.
All static content (.js, .css, .html, .png) is not seen by MVC (unless modules/runAllManagedModulesForAllRequests is set to true in web.config). Static content extensions are defined in IIS configuration "module mapping", and is using the StaticFileHandler module (and not the .NET module).
So static content must be referenced by its physical path relative to the current path (the path of the current html page).
The best solution is to use absolute link from the root of the website. Like /content/demo1/demo1.html, put all js,css in /content/demo1/, and in demo1.html use path relative to the /content/demo1/ folder (where the .html is). Ie: with demo1.css being in the same folder.
The link to demo1.html would be demo 1
I have an MVC Application with multiple Areas. They share a lot of common code and components, so I do not want to break them up into separate Projects. But I would like to deploy them to separate web sites.
The normal routing is:
www.mysharedsite.com/Area1
www.mysharedsite.com/Area2
...
But I would like to deploy them as:
www.area1site.com/
www.area2site.com/
...
I was thinking of putting a field in the web.config and then adding logic in the RouteConfig and the RegisterAreas of each area to change the Routes and turn off Routes to Controllers altogether. But this seems kludgy.
Is there a clean way of doing this?
What I would do is create and install a custom ActionInvoker which reads the hostname from the request, and based on it, sets the appropriate Area path for you:
protected override ActionResult InvokeActionMethod(...)
{
// Get hostname
var hostname = controllerContext.HttpContext.Request.Url.Host;
if (hostname == "some value you want")
{
controllerContext.RouteData.DataTokens["area"] = "your area here";
}
return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
}
You could specify a route based on the hostname, mapping it to an area. Based on the URL format in your question:
routes.Add("DomainRoute", new DomainRoute(
"{area}site.com", // Domain with parameters
"{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
));
See this post for the DomainRoute class:
http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx
Why not put the common code in a seperate dll
and link your websites to this dll?
Your solution will be a lot bigger if you add another website that also shares the common code.