开发者

using Url.Content to display the file content with .net mvc

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!开发者_Python百科
    <% 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.

Did I do something wrong? I used to display pictures this way. I guess with plain text, Url.Content doesn't work any more?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜