2012-05-24 85 views
0

我在獲取上傳文件(HTTPPostedFile)和發佈到某個動作的對象時出現問題。我有一類叫做小部件:MVC3 ::在動作中傳遞一個對象和一個HttpPostedFile

public class Widget 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string FilePath { get; set; } 
} 

,並在窗口小部件控制器我有一個「添加」方法

public ActionResult Add() 
{ 
    return View(); 
} 

和重載的方法來接受什麼樣的用戶會回

[HttpPost] 
public ActionResult Add(Widget widget, HttpPostedFile file) 
{ 
    // Save posted file using a unique 
    // Store the path/unique name in Widget.FilePath 
    // Save new Widget object 
    return View(); 
} 

並在視圖中我有以下內容:

@model Project.Models.Widget 
@{ 
    using(Html.BeginForm()) 
    { 
     Html.LabelFor(model => model.FirstName)<br /> 
     Html.TextBoxFor(model => model.FirstName)<br /> 
     Html.LabelFor(model => model.LastName)<br /> 
     Html.TextBoxFor(model => model.LastName)<br /> 
     <input type="file" id="file" /><br /> 
     <input type="submit" value="Save" /> 
    } 
} 

我想要做的是讓用戶填寫表格並選擇要上傳的文件。文件上傳後,我想使用唯一的名稱保存文件,然後將文件的路徑存儲爲widget.FilePath。

每次嘗試時,都會填充小部件對象,但uploadedFile爲空。

任何幫助將不勝感激。

回答

6

您的代碼有幾個問題。

  • 確保您已設置適當的enctype="multipart/form-data"到表單中,否則你將無法上傳任何文件。
  • 確保您的文件輸入具有name屬性,並且此屬性的值與您的動作參數的名稱相匹配。分配id對服務器端綁定沒有影響。

例如:

@model Project.Models.Widget 
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.LabelFor(model => model.FirstName)<br /> 
    @Html.TextBoxFor(model => model.FirstName)<br /> 
    @Html.LabelFor(model => model.LastName)<br /> 
    @Html.TextBoxFor(model => model.LastName)<br /> 
    <input type="file" id="file" name="file" /><br /> 
    <input type="submit" value="Save" /> 
} 

另外,還要確保你的控制器動作可與的HttpPostedFileBase代替HttpPostedFile

[HttpPost] 
public ActionResult Add(Widget widget, HttpPostedFileBase file) 
{ 
    // Save posted file using a unique 
    // Store the path/unique name in Widget.FilePath 
    // Save new Widget object 
    return View(); 
} 

你也可以合併2個參數到一個單一的視圖模型:

public class Widget 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string FilePath { get; set; } 
    public HttpPostedFileBase File { get; set; } 
} 

然後:

[HttpPost] 
public ActionResult Add(Widget widget) 
{ 
    // Save posted file using a unique 
    // Store the path/unique name in Widget.FilePath 
    // Save new Widget object 
    return View(); 
} 

終於看完下面的博客文章:http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

+0

HttpPostedFileBase - 這是我的問題 –

相關問題