2013-04-02 221 views
1

它看起来与其他问题类似,但他们遇到的所有问题都是命名HTML中的输入类型名称=“file”和控制器中的参数名称不匹配。我多次检查并重新检查了很多事情,但HttpPostedFileBase的值始终返回为null,这导致控制器中出现NullReferenceException。 下面是代码: - HTML代码: -为什么我的HttpPostedFileBase总是空?

@using (Html.BeginForm(new { enctype = "multipart/form-data" })) 
    { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>Please Fill in the following details and Upload your Design Pic</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.chest) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.chest) 
     @Html.ValidationMessageFor(model => model.chest) 
    </div> 
    <p> 
     <label for="file">Design File Pic:</label> 
     <input type="file" name="file" /> 
    </p> 
    <p> 
     <input type="submit" value="Order" /> 
    </p> 

在控制器: -

[HttpPost] 
    [Authorize] 
    public ActionResult Index(DesignOrder order, HttpPostedFileBase file) 
    { 
     string fileurl=null; 
     if (file.ContentLength > 0) { 
      fileurl = Path.Combine("../../Images/UserUploads",User.Identity.Name + file.FileName); 
      file.SaveAs(fileurl); 
     } 
    } 

错误进来行,如果(file.ContentLength> 0) - 的NullReferenceException。

回答

3

因为Html.BeginForm(object)用于RouteValues,而不是元素属性。您需要为属性使用更大的重载。试试这个:

Html.BeginForm("action", "controller", null, FormMethod.Post, new { enctype = "multipart/form-data" }) 

在这里看到我的意思:http://msdn.microsoft.com/en-us/library/dd470793(v=vs.108).aspx