使用Url.Content显示文件内容与.NET MVC [英] using Url.Content to display the file content with .net mvc
问题描述
在我的.NET MVC应用程序,我需要动态插入来自本地文件内容到一个视图页面。所以,从不同的文件中的内容可以显示具有相同风格。所以,我创建了一个名为StaticController控制器,并呼吁一般的操作。以下是我的code:
In my .net mvc application, I need to dynamically insert contents from local files into a View page. So that the contents from different files can be display with the same style. So I created a controller called StaticController and an action called General. Following is my code:
public class StaticController : Controller
{
public virtual ViewResult General(string filePath)
{
return View((object)filePath);
}
}
在我看来,我尝试用文件路径显示该文件的内容。
In my view I try to display the contents of the file with the filePath.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Tab.Master" Inherits="System.Web.Mvc.ViewPage<string>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%if(string.IsNullOrEmpty(Model)){ %>
Sorry, page is under construction!
<% return;} %>
<%=Url.Content(Model)%>
</asp:Content>
Then I tested the view with http://localhost:4789/Static/General?filePath="~/staticfiles/1.txt" and then I expect the content of 1.txt to be displayed. But all I got back is a nice "~/staticfiles/1.txt" on my screen.
难道我做错了什么?我用来显示图片这种方式。我想用纯文本,Url.Content不工作了吗?
Did I do something wrong? I used to display pictures this way. I guess with plain text, Url.Content doesn't work any more?
推荐答案
首先一个或两个注释,不知道为什么你标记你的一般操作的虚拟和第二,&LT;%= EX pression%>会返回的前pression文本。你的情况的路径,你在那么一切工作为你写它通过了。
First a comment or two, not sure why you've marked your General action as virtual and second, <%= expression %> will return the text of the expression. In your case the path you passed in so everything is working as you've written it.
其次,我想你最好离扩大如下的动作:
Secondly, I think you'd be best off expanding your Action as below:
public virtual ViewResult General(string filePath)
{
StreamReader sr = File.OpenText(Server.MapPath(filePath));
return View(sr.ReadToEnd());
}
您可以将读取到视图本身的文件,但在查看被认为是愚蠢的,只显示是什么给了。
You could move the file read into the View itself but the View is supposed to be dumb, just displaying what's given.
这篇关于使用Url.Content显示文件内容与.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!