2

好的,我已经做了几个小时了,我根本找不到解决方案。

我想从我的用户那里得到一些数据。所以首先,我使用一个控制器来创建一个接收模型的视图:

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

该控制器的其余部分无关紧要,因为无论我做什么,(or ) 的count属性都保持为 0。我根本找不到从表单传递文件的方法(模型通过就好了)。Request.FilesRequest.Files.Keys

4

2 回答 2

3

您可能要考虑不要将文件与表格的其余部分一起发布 - 有充分的理由和其他方法可以实现您想要的。

另外,查看这个问题这个关于 MVC 中文件上传的建议。

于 2010-10-07T02:53:06.010 回答
3

您可以将文件添加到您的视图模型:

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");
}
于 2010-10-07T06:25:12.867 回答