ASP.NET MVC 将模型与文件一起*传递回 Controller

标签 asp.net asp.net-mvc file-upload httppostedfile httppostedfilebase

好吧,我已经研究了几个小时,但就是找不到解决方案。

我想从我的用户那里获取一些数据。首先,我使用 Controller 创建一个接收模型的 View :

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>

最后 - 原始 Controller ,但这次配置为接受数据:

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

该 Controller 的其余部分并不重要,因为无论我做什么,Request.Filescount 属性(或 Request.Files.Keys) 仍然是 0。我根本找不到从表单传递文件的方法(模型传递得很好)。

最佳答案

您可能需要考虑不要将文件与表单的其余部分一起发布 - 有 good reasons and other ways你可以实现你想要的。

此外,请查看this questionthis advice关于MVC中的文件上传。

关于ASP.NET MVC 将模型与文件一起*传递回 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877448/

相关文章:

android - 如何在android中上传多个文件

php - 使用PHP将文件路径名保存到mySQL数据库

c# - 如何访问每个循环的 html 属性以进行编码?

asp.net - WCF 请求处理线程敏捷吗?

c# - GridView 行编辑

c# - 尝试返回 json 并填充选择列表

ASP.NET MVC 6 (vNext) 未正确链接到文件

asp.net - 如何在ASP.NET MVC网站中为cookie设置 'secure'标志?

asp.net - ASP.NET MVC 中的分页

python - Django + AWS : files not syncing to S3