2011-01-24 105 views
91

我有一个表单上传工作,但我想传递我的数据库的模型信息以保存该文件与当然不同的名称。MVC 3文件上传和模型绑定

这里是我的Razor视图:

@model CertispecWeb.Models.Container 

@{ 
    ViewBag.Title = "AddDocuments"; 
} 

<h2>AddDocuments</h2> 

@Model.ContainerNo 

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, 
      new { enctype = "multipart/form-data" })) 
{ 
    <input type='file' name='file' id='file' /> 
    <input type="submit" value="submit" /> 
} 

这里是我的控制器:

[HttpPost] 
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file) 
{ 
    if (file.ContentLength > 0) 
    { 
     var fileName = Path.GetFileName(file.FileName); 
     var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), 
         containers.ContainerNo); 
     file.SaveAs(path); 
    } 

    return RedirectToAction("Index"); 
} 

模型信息不是通过控制器通过。我读过,我可能需要更新模型,我该怎么做?

+2

参见http://stackoverflow.com/questions/9411563/asp-net-mvc3-razor-file-upload-gives-zero -as-file-count相关问题 – Lijo 2012-12-20 14:45:41

回答

124

您的表单不包含除文件之外的任何输入标签,因此在您的控制器操作中,您无法期望获得除上传文件以外的其他任何内容(即发送到服务器的所有内容)。实现这一目标的一种方法是包含一个隐藏标签,其中包含模型的id,它将允许您从发布的控制器操作中的数据存储库中检索它(如果用户不应该修改模型只需连接一个文件):

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.HiddenFor(x => x.Id) 
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="submit" /> 
} 

,然后在你的控制器动作:

[HttpPost] 
public ActionResult Uploadfile(int id, HttpPostedFileBase file) 
{ 
    Containers containers = Repository.GetContainers(id); 
    ... 
} 

在另一方面,如果你想允许用户修改这种模式,那么你将需要包括适当的为要发送到服务器的模型的每个字段输入字段:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.TextBoxFor(x => x.Prop1) 
    @Html.TextBoxFor(x => x.Prop2) 
    @Html.TextBoxFor(x => x.Prop3) 
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="submit" /> 
} 

,然后你将有默认的模型绑定从请求重建这种模式:

[HttpPost] 
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file) 
{ 
    ... 
} 
+4

非常感谢,效果很好。弗朗西斯 – Francis 2011-01-24 16:48:24

+1

我得到`文件'作为`null`和`Request.Files.Count`也是0,如果`form`是`AjaxForm`并且还有`routeValues`,那么会有什么区别吗? – bjan 2012-05-30 10:48:35

6

如果你不会总是有图片张贴到你的行动,你可以做这样的事情:

[HttpPost] 
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{ 
    //do container stuff 

    if (Request.Files != null) 
    { 
     foreach (string requestFile in Request.Files) 
     { 
      HttpPostedFileBase file = Request.Files[requestFile]; 
      if (file.ContentLength > 0) 
      { 
       string fileName = Path.GetFileName(file.FileName); 
       string directory = Server.MapPath("~/App_Data/uploads/"); 
       if (!Directory.Exists(directory)) 
       { 
        Directory.CreateDirectory(directory); 
       } 
       string path = Path.Combine(directory, fileName); 
       file.SaveAs(path); 
      } 
     } 
    } 

} 
8

解决

型号

public class Book 
{ 
public string Title {get;set;} 
public string Author {get;set;} 
} 

控制器

public class BookController : Controller 
{ 
    [HttpPost] 
    public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload) 
    { 
     throw new NotImplementedException(); 
    } 
} 

并查看控制器操作参数的

@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{  
    @Html.EditorFor(m => m) 

    <input type="file" name="fileUpload[0]" /><br />  
    <input type="file" name="fileUpload[1]" /><br />  
    <input type="file" name="fileUpload[2]" /><br />  

    <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" /> 
} 

注意标题必须输入元素的名称相匹配 IEnumerable<HttpPostedFileBase> fileUpload - >name="fileUpload[0]"

fileUpload必须匹配

1

对于多个文件;注意新的 “” 属性输入:

形式:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"})) 
{ 
    <label for="files">Filename:</label> 
    <input type="file" name="files" multiple="true" id="files" /> 
    <input type="submit" /> 
} 

控制器:

[HttpPost] 
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files) 
{ 
    return View(); 
} 
1

1日下载jquery.form.js从下面的URL文件

http://plugins.jquery.com/form/

Writ下文E代码在CSHTML

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" })) 
{ 
    <div id="uploadTemplate"> 

     <input type="text" value="Asif" id="txtname" name="txtName" /> 


     <div id="dvAddTemplate"> 
      Add Template 
      <br /> 
      <input type="file" name="file" id="file" tabindex="2" /> 
      <br /> 
      <input type="submit" value="Submit" /> 
      <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" /> 
     </div> 

     <div id="TemplateTree" style="overflow-x: auto;"></div> 
    </div> 

    <div id="progressBarDiv" style="display: none;"> 
     <img id="loading-image" src="~/Images/progress-loader.gif" /> 
    </div> 

} 


<script type="text/javascript"> 

    $(document).ready(function() { 
     debugger; 
     alert('sample'); 
     var status = $('#status'); 
     $('#frmTemplateUpload').ajaxForm({ 
      beforeSend: function() { 
       if ($("#file").val() != "") { 
        //$("#uploadTemplate").hide(); 
        $("#btnAction").hide(); 
        $("#progressBarDiv").show(); 
        //progress_run_id = setInterval(progress, 300); 
       } 
       status.empty(); 
      }, 
      success: function() { 
       showTemplateManager(); 
      }, 
      complete: function (xhr) { 
       if ($("#file").val() != "") { 
        var millisecondsToWait = 500; 
        setTimeout(function() { 
         //clearInterval(progress_run_id); 
         $("#uploadTemplate").show(); 
         $("#btnAction").show(); 
         $("#progressBarDiv").hide(); 
        }, millisecondsToWait); 
       } 
       status.html(xhr.responseText); 
      } 
     }); 

    }); 


</script> 

操作方法: -

public ActionResult Index() 
     { 
      ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

      return View(); 
     } 

public void Upload(HttpPostedFileBase file, string txtname) 
     { 

      try 
      { 
       string attachmentFilePath = file.FileName; 
       string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1); 

      } 
      catch (Exception ex) 
      { 

      } 
     }