从MVC中的目录中删除文件

时间:2014-03-05 23:46:45

标签: c# asp.net-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>
}
}

2 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分:0)

文件名应该是HTTP POST变量。

因此,您必须创建一个隐藏字段来保存文件名,以便在提交表单时可以访问操作上的值。

在动作名称上方,您将使用[HttpPost]属性,以便表单提交登陆此操作。

使用HTTP POST而不是HTTP GET是安全的,否则任何有网址的人都可以删除文件。

如果您有多个文件名,则每个隐藏字段的名称可以是filename_1,filename_2等。

我已经给你了方向去看看&amp;调查。