Can a ActionResult open a specific folder on a server? - c#

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

Related

How to specify the view name in an MVC action?

I'm learning Asp MVC.
I've been doing WPF MVVM programs for two years already, but i also need to learn ASP which is a common language used in web development in my country as far as i know. And i have also knowledge in c# so i think adjusting will not be very hard, but i'm already facing a lot of problems in making my website work. I tried reading about ASP and MVC but i learn by doing things and from my mistake than reading it. So i decided to give it a try.
I created an EMPTY MVC project using Visual Studio Community Edition 2017
I already created the Layout Page and the First Controller and the First View and its totally working fine.
This is the screenshot
Then i create the second controller. Then the problem comes in.
I created a new controller named NewPostController and ADD View for it like this
But it create another folder with the name of the View and inside it is the view it created
I don't want it to organize that way.
So i dragged the NewPost.cshtml into the admin folder. Run the application then i received an error saying
The resource cannot be found.
Requested URL: /Admin/NewPost
I did a search for a solution but i can't solve the problem
I tried specifying the view name
public ActionResult NewPost()
{
return View("~/Admin/NewPost");
}
Most of the solution i read is specify the View Name. But i can't make it work. What are the things that i missed? Or not understand? Thank you.
MVC have sort of a naming convention where if your controller is named FooController then your views should be keep in a folder name Foo.
Inside this controller you will have your
public ActionResult <name of view>
name exactly the same as the view for easy referencing.
So when you have a view under the Foo Folder and the name of that cshtml file is Hello
then inside the FooController, you have a
public ActionResult Hello(//parameter here){
//body here
}
Hope you understand my explanation.
Also to answer your question. I'm assuming you want the NewPost.cshtml as part of the admin folder. Just add
public ActionResult NewPost()
to your admin controller and then you can use
localhost/admin/NewPost()
If i miss anything or any error, please comment hehe answered this in a bit of a rush
Just move your NewPost action to your AdminController as such:
public class AdminController : Controller
{
public ActionResult Dashboard()
{
return View();
}
// Here you go
public ActionResult NewPost()
{
return View();
}
}
This is default MVC structure if you want both Dashboard and NewPost views to be in the Admin folder

asp.net MVC secure root folder only for authorized users

I am having this small extranet service where users can log in, get all sorts of info and download few files.
Is it possible to secure root folder in MVC asp.net project? I am having a project where users have to log in before using any material. How ever if I use for example "/material" folder for every pdf, jpg, etc. files, other unauthorized users can see those files also.
For example everybody can see this file if they type www.example.com/material/pdf-file.pdf So I want only authorized / logged users to see this file. Is this possible?
I managed to get it work. Here is how I did it.
The first I added this line to Web.config file:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
This allows dot chars in .pdf, .png, etc... in url's.
I added to RouteConfig.cs new routing for controller.
routes.MapRoute(
name: "Material",
url: "Material/Download/{file}",
defaults: new { controller = "Material", action = "Download", file = UrlParameter.Optional }
);
I created a new controller "Material".
// GET: Material
[Authorize]
public ActionResult Download(string file)
{
string path = Server.MapPath(String.Format("~/App_Data/Material/{0}", file));
if(System.IO.File.Exists(path))
{
string mime = MimeMapping.GetMimeMapping(path);
return File(path, mime);
}
return HttpNotFound();
}
And also transfered material folder inside app_data.
This seems to work nicely. Only authorized users can access to material folder.
It's possible to do that, but there are a lot ways to accomplish that.
A simplified scenario could be:
Disable directory listing on IIS
Create a custom "download wrapper" controller+action for the purpose of serving of those files.
Then wherever you create Action links, generate them using a HtmlHelper which would redirect the client to the "wrapper" controllers action. You can pass the filename in a parameter.
On the "wrapper" controller you could utize the [Authorize] attribute or better yet, without using such attributes everywhere you could use FluentSecurity for handling the authorization.
After you create the "wrapper" controller your URL for getting a file could look like:
www.example.com/download/file/pdf-file.pdf
This example URL assumes controller name is 'download' and action name is 'file'.

How to change name of .cshtml file on asp.net mvc?

I created a Asp.net mvc project on visual studios, In the many folder I get I have a folder called Home that has three .csthml files: about.cshtml, contact.cshtml, and index.cshtml.
I would like to change about.cshtml to blah.cshtml and contact.chstml to lala.cshtml.
I've tried to do it from properties but the name is not changed across other files in the project.
Should I use those files in my project or create another controller?
click on the file, push F2 and then rename (type in the new name) or right click the file and select rename. Make sure that you are not running the application (which may be the issue).
If you do change the name, the action in the controllers should also probably be updated.
Also, you can rename only view and then set [ViewName()] attribute for the action.
For instance, you renamed about.cshtml to blah.cshtml:
[ViewName("~/Views/Home/blah.cshtml")]
public ViewResult About()
{
...
return View();
}
However, better keep names the same

How to use resx files to manage portal content

We are developing an e-commerce system that multiple affiliate partners will use. We would like to tailor the portal for each partner and be able to accommodate slight variations in content from page to page. Our current technique has been to create a copy of a .cshtml view for each partner and make the customization to each view. Our designer is groaning because may of these views only have slight variations in wording. We only plan to have 10 or so partners (it cannot expand beyond that because of the size of our industry) so a full blown CMS system is overkill.
I would like to use resx files manage content strings for each partner the way one would use them to manage content strings for different languages. The end result would be the ability to do something like this in a view.
Please contact customer service at #Properties.Resources.PartnerCustomerServiceEmail
at not have to worry about which resource file is used to resolve the string PartnerCustomerServiceEmail.
Thank you in advance for your help
First idea that comes to my mind is to save resource file's name in question into viewdata (or Session) and use a helper to get the value.
Say you have two partners: Foo Logistics and Bar Solutions. Have a resource file for each of them: PartnerFoo.resx and PartnerBar.resx.
In your controller, store the resource file you want to use into ViewData as in:
public ActionResult About()
{
...
ViewData["Resource"] = "MyMVCAppNamespace.Resources.PartnerFoo";
return View();
}
Include the namespace into the string too.
Then code in the helper to retrieve the resource with viewdata.
Helpers/Helper.cs:
namespace MyMVCAppNamespace.MvcHtmlHelpers
{
public static class HtmlHelpersExtensions
{
public static ResourceManager PartnerResource(this HtmlHelper helper)
{
// Get resource filename from viewdata
string res = helper.ViewContext.ViewData["Resource"].ToString();
// Load the resource from assembly
ResourceManager resourceManager = new ResourceManager(res, Assembly.GetExecutingAssembly());
return resourceManager;
}
}
}
Now in the view, we are gonna use this helper to retrieve the string we want to write:
About.cshtml:
#Html.PartnerResource().GetString("PartnerName")
#Html.PartnerResource().GetString("PartnerCustomerServiceEmail")
Which gets rendered as:
Foo Logistics service#foologistics.com
or with PartnerBar
Bar Solutions service#barsolutions.com
We determine the resource file to use before the view is loaded. Then in view it gets dynamically rendered according to what resource is stored in to the viewdata. You can even store the resource filename into web.config and load the string in helper from there if you want.
What's even more cool is that if you have localized resx file, say PartnerFoo.fi.resx and then use different culture (fi-FI in this case), the resourcemanager automatically looks up the localized version.
You can even do simple branding by storing image URLs and whatnot in the resource file.
It's simple really, but I hope it gets you started.

Need help adding download feature to MVC application

I have a web MVC application that I would like to add feature that gives users the ability to download large files from my server. The users have a combination of Mac and Windows PC. I was thinking along the lines of javasripts or silverlight.
Can someone advice me on how to implement this feature?
Do you have any code examples?
Use the File method of Controller class.
So Create a Controller called FilesController and have an action method called DownLoad
public class FilesController : Controller
{
public ActionResult Download(string fileId)
{
var fullFilePath=FileService.GetFullPath(fileId); // get the path to file
return File(fullFilePath,"application/pdf","yourDownLoadName.pdf");
}
}
This Will return a PDF file from the specified path(fullFilePath) with the MimeType/ContentType as PDF and "yourDownLoadName.pdf" as the Downloadable file name
Users can access this like http://yourdomainname.com/Files/Download?fileId=somefileId
This method has got a bunch of overloads using file path, byte array ,stream etc..
Create a controller action with a FileStreamResult return type.

Categories