2012-11-09 79 views
0

我有一個包含局部視圖的主視圖。部分視圖的模型有1個屬性,名爲「HttpPostedFileBase文件」,與其他屬性一起帶部分視圖的HttpPostedFileBase

但是,當主視圖發佈時,該模型中的所有其他屬性都會得到正確的值,但「HttpPostedFileBase文件」爲空。我已經設置了與參數相同的名稱。甚至Request.Files也給我0個文件。

我做錯了什麼?

P.S.我的主視圖實際上有2個部分視圖。一個PV具有與主視圖相同的模型。第二個是我上面提到的。該模型包含對象列表和HttpPostedFileBase文件。這樣的代碼:

public class MyPartialViewModel 
{ 
    public List<MyObject> objInfos { get; set; } 


    public ICollection<HttpPostedFileBase> file { get; set; } 
} 

而在PV I looply使用@ Html.EditFor(型號=> model.objInfos [I]),將它與模板結合。

所以在主視圖後的方法,我可以得到「objInfos」列表&所有項目的值正確。但對於「文件」只是NULL。

回答

1

嘗試在@Html.BeginForm()幫助程序中將enctype = "multipart/form-data"作爲htmlAttributes之一添加。

編輯:爲了不使視覺完全回發:

AJAX FILE Upload in MVC3 using iFrame

在我使用這個方法,這合適的時機,其實實現這個,因爲我們寫的。

+0

其實我加入這樣的:@using(Ajax.BeginForm( 「MyAction」, 「myController的」,新AjaxOptions { 列舉HTTPMethod = 「POST」, UpdateTargetId = 「主變速段」, 的onSuccess = 「handleSuccess」, OnFailure =「handleError」 },new {enctype =「multipart/form-data」})) {} – Samuel

+0

它仍然是NULL – Samuel

+0

啊,那就是問題所在。爲了成功上傳文件,需要完整的回傳。使用Ajax進行上傳是不可能的。 – Romias

1

我剛剛遇到同樣的問題,並通過在ActionResult中添加一個額外的參數來採取文件上傳參數來解決此問題。

[Authorize] 
    [HttpPost] 
    public ActionResult MyActionResult(MyViewModel viewModel, HttpPostedFileBase myFileToUpload) 
    { 
     myViewModel.PartialViewModel.MyFileToUpload = myFileToUpload; 
      //manually bind MyFileToUpload; 
      //for some reason, because it's in the Partial View and it's of type HttpPostedFileBase, it won't post. 

     return View(viewModel); 
    } 

只爲背景:

我PartialViewModel包含代碼:

public HttpPostedFileBase MyFileToUpload{ get; set; } 

和PartialView代碼:

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

最後,我有一個EditorTemplate查看/共享/ EditorTemplates/HttpPostedFileBase.cshtml:

@model HttpPostedFileBase 
<input type="file" name="@ViewData.ModelMetadata.PropertyName" /> 

這是一個解決方法,而不是一個解決方案,但確實可以讓您在PartialViewModel中保留HttpPostedFileBase的同時上傳文件。