MVC:如何文件上传和其他表单字段张贴到一个动作 [英] MVC: How to post File Upload and other form fields to one action

查看:204
本文介绍了MVC:如何文件上传和其他表单字段张贴到一个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个 DocumentController 需要上载每个doument的缩略图中的库中的文档库应用程序。我想保持文件上传字段中有相同创建/编辑形式,其他字段(标题,描述,类别编号等)上。结果
问题是我不知道我是否可以混合或巢的形式标记

I am creating a document library application with a DocumentController that needs to upload a thumbnail image of each doument in the library. I want to keep the File Upload field on the same Create/Edit form as the other fields (Title, Description, CategoryId etc).
The problem is I'm not sure if I can mix or nest the form tags for

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>

我的控制器只需要文档模型和 HttpPostedFileBase ,并尝试将文件上传到服务器和文档保存到存储库

My controller just takes the Document model and HttpPostedFileBase and tries to upload the file to the server and save the Document to the repository

 [HttpPost]
 public ActionResult Create(Document document, HttpPostedFileBase uploadFile)
 {

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

      }

       return View("List");
  }

所以我想知道如果它是可以做到的文件上传和更新相同的动作库,我应该如何构造我观,以促进这一点。

So I'm wondering if it is possible to do the file upload and update the repository on the same action and how should I structure my View to facilitate this.

推荐答案

我在史蒂夫·桑德森的伟大的书看看(临ASP.NET MVC 2框架)和他的体育用品店示例应用程序,其中有一个标准的文件上传表单形成了文件上传的multipart / form-data的元素混合元素。所以它看起来像多部分类型足以使页面上的所有表单元素。虽然上传的图片被保存在数据库中,我相信我可以在相同的动作中做一个file.SaveAs()。感谢桑德森先生。希望你不介意我你重现code ...

I had a look in Steve Sanderson's great book (Pro ASP.NET MVC 2 Framework) and his Sports Store sample application has a file upload form where there are standard form elements mixed with a file upload "multipart/form-data" element. So it looks like the multipart type suffices for all form elements on the page. Although the uploaded image is being saved in the db I'm sure I can do a file.SaveAs() within the same Action. Thanks Mr. Sanderson. Hope you dont mind me reproducing your code...

查看

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

控制器

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

这篇关于MVC:如何文件上传和其他表单字段张贴到一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆