2014-02-24 80 views
10

我有这个控制器和我所试图做的是将图像发送到控制器的(字节),这是我的控制器:MVC HttpPostedFileBase总是空

[HttpPost] 
public ActionResult AddEquipment(Product product, HttpPostedFileBase image) 
{ 

      if (image != null) 
      { 
       product.ImageMimeType = image.ContentType; 
       product.ImageData = new byte[image.ContentLength]; 
       image.InputStream.Read(product.ImageData, 0, image.ContentLength); 
      } 

      _db.Products.Add(product); 
      _db.SaveChanges(); 

      return View(); 
} 

和我的看法:

@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post)) { 

    <fieldset> 
     <legend>Product</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Description) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Description) 
      @Html.ValidationMessageFor(model => model.Description) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Price) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Price) 
      @Html.ValidationMessageFor(model => model.Price) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Category) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Category) 
      @Html.ValidationMessageFor(model => model.Category) 
     </div> 

     <div> 
     <div>IMAGE</div> 
     <input type="file" name="image" /> 

     </div> 


     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

但问题是,我的控制器上的图像值常是空的,我不能似乎得到的HttpPostedFileBase任何信息

回答

23

您需要与万亩添加encType ltipart /形式数据。

@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) { 

您可以随时将其添加到您的模型太如下,只要它是一个ViewModel:

public class Product 
{ 
    public Product() 
    { 
     Files = new List<HttpPostedFileBase>(); 
    } 

    public List<HttpPostedFileBase> Files { get; set; } 
    // Rest of model details 
} 

您可以通过即

[HttpPost] 
public ActionResult AddEquipment(Product product) 
{ 
    var file = model.Files[0]; 
    ... 
} 
去除未所需参数检索的文件
+0

真棒!感谢您的快速响应! –

+0

@RiquelmyMelara没有probs,我也会改善答案。 – hutchonoid

+0

他的“产品”对象是我猜实体框架“实体”类型,因此添加另一个属性可能会破坏他的代码,除非他修复了配置 –

0

尝试在Action方法的顶部执行此操作:

[HttpPost] 
    public ActionResult AddEquipment(Product product, HttpPostedFileBase image) 
    { 
     image = image ?? Request.Files["image"]; 
     // the rest of your code 
    } 

和形式应该有 “的multipart/form-data的” 的加密类型上传文件:

@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) {