asp.net-mvc - MVC:如何将文件上传和其他表单字段发布到一个操作

标签 asp.net-mvc forms file-upload asp.net-mvc-2

我正在使用DocumentController创建一个文档库应用程序,该应用程序需要上传库中每个副本的缩略图。我想将“文件上传”字段与其他字段(标题,描述,CategoryId等)保留在相同的“创建/编辑”表单上。
问题是我不确定是否可以混合或嵌套用于

Html.BeginForm("Create", "Document", FormMethod.Post, enctype = "multipart/form-data")


Html.BeginForm()

我的看法如下:
 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Publications.WebUI.Models.DocumentEditViewModel >" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <fieldset>
        <legend>Edit
            <%=  Html.Truncate(Model.Document.Title, 50)%></legend>
        <%= Html.ValidationSummary(false) %>
        <% using (Html.BeginForm())
           { %>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Document.Title) %>
        </div>
        <div class="editor-field">
            <%= Html.HiddenFor(model => model.Document.DocumentId ) %>
            <%= Html.ValidationMessageFor(model => model.Document.Title) %>
            <%= Html.TextBoxFor(model => model.Document.Title)%>
        </div>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Document.DocumentUrl)%>
        </div>
        <div class="editor-field">
            <%= Html.ValidationMessageFor(model => model.Document.DocumentUrl)%>
            <%= Html.TextBoxFor(model => model.Document.DocumentUrl)%>
        </div>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Document.Description)%>
        </div>
        <div class="editor-field">
            <%= Html.ValidationMessageFor(model => model.Document.Description)%>
            <%= Html.TextAreaFor(model => model.Document.Description) %>
        </div>
        <div class="editor-label">
            <%= Html.LabelFor(model => model.Document.ThumbnailUrl )%>
        </div>
        <div class="editor-field">
            <% using (Html.BeginForm("Create", "Document",
                    FormMethod.Post, new { enctype = "multipart/form-data" }))
               {%>
            <%= Html.ValidationMessageFor(model => model.Document.ThumbnailUrl )%>
            <input name="uploadFile" type="file" />
            <% } %>
        </div>
        <div class="formActions">
            <div class="backNav">
                <%= Html.ActionLink("< Back to List", "Index") %>
            </div>
            <div class="submit">
                <input type="submit" value="Save" />
            </div>
            <% } %>
        </div>
    </fieldset>
</asp:Content>

我的 Controller 仅采用Document模型和HttpPostedFileBase并尝试将文件上传到服务器并将Document保存到存储库
 [HttpPost]
 public ActionResult Create(Document document, HttpPostedFileBase uploadFile)
 {

     if (ModelState.IsValid)
     {
         //Process file upload
         //Update repository

      }

       return View("List");
  }

因此,我想知道是否可以通过相同的操作上传文件并更新存储库,以及如何构造 View 来简化此操作。

最佳答案

我看过史蒂夫·桑德森(Steve Sanderson)的精彩著作(Pro ASP.NET MVC 2 Framework),他的体育用品商店示例应用程序具有文件上传表单,其中包含标准表单元素和文件上传“multipart / form-data”元素。因此,看起来多部分类型足以满足页面上的所有表单元素。尽管上传的图像已保存在数据库中,但我确定可以在同一Action中执行file.SaveAs()。谢谢桑德森先生。希望你不介意我重现你的代码...

查看

    <asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <h1>Edit <%= Model.Name %></h1>

    <% using (Html.BeginForm("Edit", "Admin", FormMethod.Post, 
                             new { enctype = "multipart/form-data" })) { %>
        <%= Html.Hidden("ProductID") %>
        <p>
            Name: <%= Html.TextBox("Name") %>
            <div><%= Html.ValidationMessage("Name") %></div>
        </p>
        <p>
            Description: <%= Html.TextArea("Description", null, 4, 20, null) %>
            <div><%= Html.ValidationMessage("Description") %></div>
        </p>
        <p>
            Price: <%= Html.TextBox("Price") %>
            <div><%= Html.ValidationMessage("Price") %></div>
        </p>
<p>
    Category: <%= Html.TextBox("Category") %>
    <div><%= Html.ValidationMessage("Category") %></div>
</p>
<p>
    Image:
    <% if(Model.ImageData == null) { %>
        None
    <% } else { %>
        <img src="<%= Url.Action("GetImage", "Products", 
                                 new { Model.ProductID }) %>" />
    <% } %>
    <div>Upload new image: <input type="file" name="Image" /></div>                
</p>

<input type="submit" value="Save" /> &nbsp;&nbsp;
        <%=Html.ActionLink("Cancel and return to List", "Index") %>
    <% } %>
</asp:Content>

CONTROLLER
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Product product, HttpPostedFileBase image)
    {
        if (ModelState.IsValid) {
            if (image != null) {
                product.ImageMimeType = image.ContentType;
                product.ImageData = new byte[image.ContentLength];
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }
            productsRepository.SaveProduct(product);
            TempData["message"] = product.Name + " has been saved.";
            return RedirectToAction("Index");
        }
        else // Validation error, so redisplay same view
            return View(product);
    }

关于asp.net-mvc - MVC:如何将文件上传和其他表单字段发布到一个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5149116/

相关文章:

javascript - dropzonejs 文件类型

javascript - 创建 div id concating 变量和字符串

asp.net - 我可以在 Visual Studio 2010 中将任务列表项添加到 csHTML 中吗?

c# - 使用查询字符串设置下拉列表中的选择

php - move_uploaded_file() 函数不会将上传的文件保存在服务器上

file-upload - 将附加元数据作为文件上传请求的一部分上传到 Google Cloud Storage

asp.net-mvc - MVC所见即所得的编辑器?

asp.net-mvc - 如何在 ASP.NET MVC 中的 MVC 上动态显示字符串/ bool 对的名称和值的列表

ruby-on-rails - 单个数据库条目 rails 3 的多个文本字段

python - 如何请求 HTML 中多重选择的所有元素?