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")
and
Html.BeginForm()
My view is as follows:
<%@ 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>
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…