Pergunta

Ok, I've been going at this for several hours and I simply cannot find the solution.

I want to get some data from my user. So first, I use a controller to create a view which receives a Model:

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

Then, I have the view:

<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>

and finally - the original controller, but this time configured to accept the data:

   [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;
            }

The rest of this controller does not matter since no matter what I do, the count attribute of Request.Files (or Request.Files.Keys) remains 0. I simply can't find a way to pass the files from the form (the Model passes just fine).

Foi útil?

Solução

You might want to consider not posting the files with the rest of the form- there are good reasons and other ways you can achieve what you want.

Also, check out this question and this advice regarding file uploads in MVC.

Outras dicas

You could add the files to your view model:

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

And then:

[HttpPost]
public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
{
    if (ModelState.IsValid)
    {
        // Use dataFromUser.File1 and dataFromUser.File2 directly here
    }
    return RedirectToAction("index");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top