[英]ASP.NET MVC3 Upload a file from a Partial view (and fill the corresponding field in the Model)
我知道這個問題已經在SO和其他地方討論過了 ,但我找不到任何問題的答案。
我正在開發一個ASP.NET MVC3項目,我想創建一個包含FileUpload
的Partial視圖 。 在基本的Create
頁面上調用此局部視圖,我希望要上載的文件屬於要創建的模型。 只有當用戶提交表單時,才會上傳所選文件。
以下是代碼的解釋:
Model ModelToCreate
public class ModelToCreate
{
//Some properties
public FileUploadModel Files { get; set; }
}
模型FileUploadModel
public class FileUploadModel
{
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
我的PartialView(_UploadFiles.cshtml)
@model Models.ModelToCreate
//I tried with Html.BeginForm(Create, MyController instead of null, null, but with no result.
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })
}
如何調用局部視圖(通過Create.cshtml)
@Html.Partial("_UploadFiles")
我也試過@Html.Partial("_UploadFiles", Model)
,但沒有結果......
當我單擊Create.cshtml
的“ Submit
按鈕時,表單將提交給我的控制器。“ Files
字段始終為null
而其他數據則為“正常”。
我錯過了什么嗎? 你能指出我的位置(為什么?)
謝謝 !
更新(和解決方案)
這里有一些我忘記了Create.cshtml
的附加信息表單如下所示:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form" }))
{
// Some fields, Textboxes and others CheckBoxes
//Call to partial View
}
當我看一下生成的源代碼時,我在<form>
標簽中看到了局部視圖...所以我在<tag>
中有一個<tag>
,這是非法的並且“被忽略”。 這導致了問題
解決方案只需將此標記添加到Create.cshtml的Create.cshtml
:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "target-form", enctype = "multipart/form-data" }))
並將我的部分視圖稱為
@Html.Partial("_UploadFiles", Model)
好的,這將使它適合你。
Create.cshtml
視圖(將表單和提交移動到部分之外)
@using(Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.Partial("_UploadFiles", Model)
<input type="submit" value="submit" />
}
_UploadFiles.cshtml
視圖
@model ModelToCreate
@Html.TextBoxFor(m => m.Files.Files, new { type = "file", name = "Files" })
模型(更改為列表並注意FileUploadModel
構造函數中的初始化程序)。
public class ModelToCreate
{
//Some properties
public FileUploadModel Files { get; set; }
}
public class FileUploadModel
{
public FileUploadModel()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
}
控制器動作:
public ActionResult Create()
{
var model = new ModelToCreate();
return View(model);
}
[HttpPost]
public ActionResult Create(ModelToCreate model)
{
var file = model.Files.Files[0];
return View(model);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.