質問

わかりました、私はこれに数時間行ってきましたが、解決策を見つけることができません。

ユーザーからデータを取得したいです。したがって、最初に、コントローラーを使用して、モデルを受信するビューを作成します。

public ViewResult CreateArticle()
{
    Article newArticle = new Article();
    ImagesUploadModel dataFromUser = new ImagesUploadModel(newArticle);
    return View(dataFromUser);
}

それから、私は見解を持っています:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

    <h2>AddArticle</h2>

    <% using (Html.BeginForm("CreateArticle", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" })){ %>


                <%= Html.LabelFor(model => model.newArticle.Title)%>
                <%= Html.TextBoxFor(model => model.newArticle.Title)%>

                <%= Html.LabelFor(model => model.newArticle.ContentText)%>
                <%= Html.TextBoxFor(model => model.newArticle.ContentText)%>

                <%= Html.LabelFor(model => model.newArticle.CategoryID)%>
                <%= Html.TextBoxFor(model => model.newArticle.CategoryID)%>

                <p>
                    Image1: <input type="file" name="file1" id="file1" />
                </p>
                <p>
                    Image2: <input type="file" name="file2" id="file2" />
                </p>

            <div>
                <button type="submit" />Create
            </div>



    <%} %>


</asp:Content>

そして最後に - 元のコントローラーですが、今回はデータを受け入れるように構成されています。

   [HttpPost]
    public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
    {
        if (ModelState.IsValid)
        {
            HttpPostedFileBase[] imagesArr;
            imagesArr = new HttpPostedFileBase[2]; 
            int i = 0;
            foreach (string f in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[f];
                if (file.ContentLength > 0)
                    imagesArr[i] = file;
            }

私が何をしても、このコントローラーの残りは重要ではありません。 count の属性 Request.Files (また Request.Files.Keys)0のままです。フォームからファイルを渡す方法を見つけることができません(モデルは正常に渡されます)。

役に立ちましたか?

解決

フォームの残りの部分でファイルを投稿しないことを検討したい場合があります - 正当な理由やその他の方法 あなたはあなたが望むものを達成することができます。

また、チェックしてください この質問このアドバイス MVCのファイルアップロードについて。

他のヒント

ビューモデルにファイルを追加できます。

public class ImagesUploadModel
{
    ...
    public HttpPostedFileBase File1 { get; set; }
    public HttpPostedFileBase File2 { get; set; }
}

その後:

[HttpPost]
public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
{
    if (ModelState.IsValid)
    {
        // Use dataFromUser.File1 and dataFromUser.File2 directly here
    }
    return RedirectToAction("index");
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top