2014-03-05 239 views
0

我在一年前編寫了一些MVC代碼,而且我對框架的瞭解似乎已經消失。在下面的代碼塊中,我列出了一個目錄中的所有文件,並提供了一個鏈接以下載它們(用於已認證的用戶)。我想要做的是提供刪除每個文件的選項。我剛剛添加了一個刪除按鈕,但我不知道該從哪裏去。從MVC目錄中刪除文件

@{IEnumerable<string> enumerateFiles = Directory.EnumerateFiles(Server.MapPath("~/Content/Documents"));} 
@{ 
    if (Request.IsAuthenticated) 
    { 
     <h3>Authenticated User: @User.Identity.Name</h3> 
     <h4>-Downloadable Files-</h4> 
<ul> 

    @foreach (var fullPath in enumerateFiles) 
    {   
     var fileName = Path.GetFileName(fullPath); 

      <li> <a href="../../Content/Documents/@fileName"> @fileName</a> 
      <button type="button" id="fileRemover" value="Delete" onclick="return confirm('Are you sure?')" >Delete</button> 
      </li> 
    } 
</ul> 
    } 
else 
{ 
    <h3>Non-Authenticate User, register and/or login to see documents</h3> 
} 
} 
+1

您應該將所有C#移出視圖。這將重新調整您對服務器端和客戶端之間差異的記憶。 –

回答

0

查看文件和刪除文件的代碼應包含在控制器中。您的視圖僅用於將信息(通常來自您的模型)顯示給用戶。

如果我是你,我會組織我的控制器是這樣的:

public class FilesController : Controller 
{ 
    public ActionResult List() 
    { 
     List<FileInfo> model = new List<FileInfo>(); 
     // Grab all file names from the directory and place them within the model. 

     return View(model); 
    } 

    public ActionResult View(string fileName) 
    { 
     // Add header for content type 
     // Grab (and verify) file based on input parameter fileName 

     return File(...); 
    } 

    public ActionResult Delete(string fileName) 
    { 
     // Verify file exists 
     // Delete file if it exists 

     return RedirectToAction("List"); 
    } 
} 
+0

這是我嘗試做的第一件事。我無法弄清楚如何將文件名傳遞給刪除操作。我在視圖內@using(Html.BeginForm(「Delete」,「Home」,FormMethod.Post)) { } – flaVius

+0

根據上面的示例,有兩種方法可以完成:a)刪除具有文件名的鏈接作爲查詢字符串的一部分(假定您的刪除操作可以使用GET HTTP動詞)。類似於:Delete b)點擊刪除按鈕時會觸發一點JavaScript。 JavaScript將填充隱藏的表單字段(id =「fileName」)。填充隱藏字段後,請提交表單。 –

0

的文件名應該作爲一個HTTP POST變量。

因此,您必須創建一個隱藏字段來保存文件名,以便您可以在提交表單時訪問該操作的值。

在動作名稱上方,您將使用[HttpPost]屬性,以便表單提交登錄此動作。

可以安全地使用HTTP POST而不使用HTTP GET,否則具有url的任何人都將能夠刪除文件。

如果你有多個文件名,然後每個隱藏域可以有名稱filename_1,filename_2等

我已經給你的方向在哪裏看&調查。