如何使用MVC在部分视图中上传文件? [英] How do I making file upload in a partial view using MVC?

查看:60
本文介绍了如何使用MVC在部分视图中上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用mvc开发一个文件上传,但是它会在多个视图中使用,所以我必须将它作为局部视图应用,我该如何制作?

I was developing a file upload in mvc but it will be used in more than one view so I have to applying it as a partial view how can I make it?

推荐答案

创建一个名为FileUploadController的新Controller,并添加两个动作结果如下

Create a new Controller named FileUploadController and add two action result like below
public class FileUploadController : Controller
 {
     //
     // GET: /FileUpload/

     public ActionResult Index()
     {
         return View();
     }
     public ActionResult UploadFile()
     {
         var httpPostedFileBase = Request.Files["FileName"];
         if (httpPostedFileBase != null && httpPostedFileBase.ContentLength > 0)
         {
             string extension = System.IO.Path.GetExtension(httpPostedFileBase.FileName);
             string path1 = string.Format("{0}/{1}", Server.MapPath("~/SavedFiles"),  extension);
             if (System.IO.File.Exists(path1))
                 System.IO.File.Delete(path1);

             httpPostedFileBase.SaveAs(path1);
         }
         ViewData["Status"] = "Success";
         return View("Index");
     }
 }





右键单击索引操作并创建如下所示的索引视图



Right click the Index action and create an index view like below

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
//like wise you can call the fileupload partial view in multiple views
        @Html.Partial("_FileUpload")
    </div>
</body>
</html>





右键单击Views文件夹中的FileUpload文件夹并创建局部视图(可以查看局部视图窗口中的复选框)名为_FileUpload并粘贴如下代码



Right click FileUpload folder inside Views folder and create a Partial View(You can check partial view checkbox from the window) named _FileUpload and paste the code like below

@using(Html.BeginForm("UploadFile","FileUpload",FormMethod.Post,new{enctype="multipart/form-data"}))
{
    <input type="file" name="FileName" id="file" style="width:240px"/>
    <input type="submit" value="Upload"/>
}





您可以在多个页面中调用此部分视图,就像我们在索引视图中调用的那样

希望这有助于



You can call this partial view in multiple pages like we have called in index view
Hope this helps


这篇关于如何使用MVC在部分视图中上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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