使用Url.Content显示文件内容与.NET MVC [英] using Url.Content to display the file content with .net mvc

查看:120
本文介绍了使用Url.Content显示文件内容与.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>

然后,我测试了 HTTP的观点://本地主机:4789 /静态/通用文件路径= < /a>"~/staticfiles/1.txt,然后我希望要显示的1.txt的内容。但是,所有我回来是一个很好的我的屏幕上的〜/ staticfiles / 1.TXT。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆