2011-07-12 40 views
1

我有很多靜態HTML文件(讓我們說1.html到100.html)。有沒有什麼辦法可以創建一個像Files/get/1這樣的鏈接(其中「Files」是控制器,「get」是動作)。根據傳遞的ID讀取文件,並將文件內容放入我的網站佈局中併發送給用戶。將HTML內容添加到MVC(無AJAX)動態視圖

通過這種方式,這些Html文件的格式將被保留,並且我不需要爲每個文件創建一個View。

我是新來的MVC,並會欣賞任何建議/提示。如果問題不明確,請告知我。

感謝您的幫助提前。 Reza,

編輯:添加了我最終做的。

回答:所以我使用了Darin下面說的,將它與一點jQuery結合起來,得到了我所需要的。這是我的佈局中加載靜態HTML文件。下面是我所做的樣本:

首先,我創造了我的控制器兩種方法:

public ActionResult GetHelp(String id) 
    { 
     var folder = Server.MapPath(Config.get().Help_Folder); 
     var file = Path.Combine(folder, id + ".html"); 
     if (!System.IO.File.Exists(file)) 
     { 
      return HttpNotFound(); 
     } 
     return Content(System.IO.File.ReadAllText(file), "text/html"); 

    } 


    public ActionResult GetHelper(String id) 
    { 

     ViewBag.helpPath = id; 
     return View(); 

    } 

然後,我創建了一個名爲調用getHelper視圖,它使用我的佈局,並添加下面的代碼到它:

<script type="text/javascript"> 

$(function() { 
    var path = "@ViewBag.helpPath" 
    path = "@Url.Content("~/Helps/GetHelp/")" + path; 
    $('#help-content').load(path); 

}); 
</script> 

<div id="help-content"> 

</div> 

它完美的工作。唯一的缺點是對每一頁我們得到兩個服務器請求:(在電線之間

回答

2

東西:

public class FileController : Controller 
{ 
    public ActionResult Index(string id) 
    { 
     var folder = Server.MapPath("~/SomePathForTheFiles"); 
     var file = Path.Combine(folder, id + ".html"); 
     if (!System.IO.File.Exists(file)) 
     { 
      return HttpNotFound(); 
     } 
     return Content(System.IO.File.ReadAllText(file), "text/html"); 
    } 
} 

,如果你想要的用戶做下載這些文件:

return File(file, "text/html", Path.GetFileName(file)); 

而且由於這些是靜態文件,您可以通過裝飾控制器的動作使用[OutputCache]屬性來緩存它們:

[OutputCache(Location = OutputCacheLocation.Downstream, Duration = 10000, VaryByParam = "id")] 
public ActionResult Index(string id) 
+0

謝謝,這正是我需要的。 – Reza

+0

另一個問題。有什麼方法可以將我的佈局添加到它嗎? – Reza

+0

@Reza,你想將你的動態'_Layout.cshtml'應用到你的靜態HTML文件?在這種情況下,這些HTML文件是整個HTML頁面還是隻有HTML片段?你到底想要在佈局中呈現這個HTML片段?在@RenderBody()位置? –