2011-05-12 61 views
0
@using (Html.BeginForm("Edit", "MyController", FormMethod.Post, new { enctype="multipart/form-data"})) 
{ 
@Html.EditorFor(model => model.Name) 
<input type="file" name="fileUpload" id="fileUpload" /> 
<input type="image" name="imb_save" src="/button_save.gif" alt="" value="Save" /> 
} 

提交的表單和模型,這個動作被傳遞:形式集合不包含輸入文件(ASP.Net MVC 3)

[HttpPost] 
public ActionResult Edit(MyModel mymodel, FormCollection forms) 
{ 
     if (string.IsNullOrEmpty(forms["fileUpload"])) 
     { 
        //forms["fileUpload"] does not exist 
     } 
     //TODO: something... 
} 

爲什麼不表單包含文件上傳?但它包含其他輸入。我怎樣才能獲得我的上傳者的內容? 謝謝。

回答

3

看看在following blog post在ASP.NET MVC處理文件的上傳。你可以在你的控制器,而不是FormCollection使用HttpPostedFileBase

[HttpPost] 
public ActionResult Edit(MyModel mymodel, HttpPostedFileBase fileUpload) 
{ 
    if (fileUpload != null && fileUpload.ContentLength > 0) 
    { 
     // The user uploaded a file => process it here 
    } 

    //TODO: something... 
} 

你也可以將您的視圖模型的這fileUpload部分:

public class MyModel 
{ 
    public HttpPostedFileBase FileUpload { get; set; } 

    ... 
} 

然後:

[HttpPost] 
public ActionResult Edit(MyModel mymodel) 
{ 
    if (mymodel.FileUpload != null && mymodel.FileUpload.ContentLength > 0) 
    { 
     // The user uploaded a file => process it here 
    } 

    //TODO: something... 
} 
+0

但是爲什麼這樣的在這種[案例]的方式正常工作(http://stackoverflow.com/questions/297954/uploading-files-with-asp-net-mvc-get-name-but-no-file-stream-what-am-i -doing-W)? – greatromul 2011-05-12 07:13:18

+0

@greatromul,在這個例子中它們使用'Request.Files [「FileBlob」]來獲取實際的文件,而不是從FormCollection中獲取它。所以在你的代碼中你可以做'var file = Request.Files [「fileUpload」];'。但無論如何,我會強烈建議你使用'HttpPostedFileBase'。 – 2011-05-12 07:14:54

+0

@greatromul,爲哪個對象?嘗試遵循博客文章中顯示的確切步驟。然後適應你的情況。 – 2011-05-12 07:34:06