2011-07-09 49 views
3

我不喜歡有我除了視圖模型參數使用的參數在我POST操作方法。但是,對於使用Telerik Upload幫助程序進行文件上傳,似乎我不得不這樣做。發佈的值爲IEnumerable<HttpPostedFileBase>。有沒有什麼辦法可以將它綁定到模型上,而無需使用自定義模型綁定。怎樣包括我MVC3模型綁定一個Telerik的文件上傳?

回答

2

我不喜歡必須使用參數 我POST操作方法除了 我的視圖模型參數。

我也不是。這就是爲什麼我使用視圖模型:

public class MyViewModel 
{ 
    public IEnumerable<HttpPostedFileBase> Files { get; set; } 
    public string Foo { get; set; } 
    public string Bar { get; set; } 
    ... 
} 

然後:

[HttpPost] 
public ActionResult Upload(MyViewModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     return View(model); 
    } 

    if (model.Files != null) 
    { 
     foreach (var file in model.Files) 
     { 
      if (file != null && file.ContentLength > 0) 
      { 
       // process the uploaded file 
      } 
     } 
    } 
    ... 
} 
+0

感謝@Darin。你會注意到我沒有說我是用視圖模型仔細檢查,但如果上傳客氣模型綁定,爲你指示,我一定是做錯了什麼我的視圖模型文件的屬性爲null。 – ProfK

+0

@ProfK,是的,這可能是你一直在做的事情是錯誤的。不幸的是,由於你沒有顯示你到底在做什麼,我沒有看到我可以如何進一步幫助你。 –

+0

我的大哎呀。我在視圖模型中將Files屬性設置爲私有。 – ProfK

0

記住控件的名稱(上載()名稱(***)。)應該是同型號的財產。

public class MyViewModel 
{ 
    public IEnumerable<HttpPostedFileBase> ManyFiles { get; set; } 
    ... 
} 
// ... 
@Html.Kendo().Upload().Name("ManyFiles") 

public class MyViewModel 
{ 
    public HttpPostedFileBase OneFile { get; set; } 
    ... 
} 
// ... 
@Html.Kendo().Upload().Name("OneFile").Multiple(false)