簡體   English   中英

ASP.NET MVC3從部分視圖上載文件(並填充模型中的相應字段)

[英]ASP.NET MVC3 Upload a file from a Partial view (and fill the corresponding field in the Model)

我知道這個問題已經在SO和其他地方討論 ,但我找不到任何問題的答案。

我正在開發一個ASP.NET MVC3項目,我想創建一個包含FileUploadPartial視圖 在基本的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM