好吧,我已经研究了几个小时,但就是找不到解决方案。
我想从我的用户那里获取一些数据。首先,我使用 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.Files
的 count
属性(或 Request.Files.Keys
) 仍然是 0。我根本找不到从表单传递文件的方法(模型传递得很好)。
最佳答案
您可能需要考虑不要将文件与表单的其余部分一起发布 - 有 good reasons and other ways你可以实现你想要的。
此外,请查看this question和 this advice关于MVC中的文件上传。
关于ASP.NET MVC 将模型与文件一起*传递回 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877448/