ASP.NET MVC通过模型 *一起 *将文件返回控制器
-
28-09-2019 - |
题
好的,我已经去了几个小时了,我根本找不到解决方案。
我想从用户那里获取一些数据。因此,首先,我使用控制器创建接收模型的视图:
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;
}
该控制器的其余部分无关紧要,因为无论我做什么, count
属性 Request.Files
(或者 Request.Files.Keys
)保留0。我根本找不到一种从表单中传递文件的方法(模型通过了正常)。
解决方案
您可能要考虑不要使用其余表单上发布文件 - 充分的理由和其他方式 您可以实现想要的东西。
其他提示
您可以将文件添加到视图模型:
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");
}
不隶属于 StackOverflow