好吧,我已经研究了几个小时了,但我根本找不到解决方案。
我想从我的用户那里获取一些数据。首先,我使用控制器创建一个接收模型的视图:
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
(or Request.Files.Keys
)仍然是 0。我根本找不到从表单传递文件的方法(模型传递得很好)。
您可能需要考虑不要将文件与表格的其余部分一起发布 - 有充分的理由和其他方法 https://stackoverflow.com/questions/851318/asp-net-mvc-1-to-many-saving-post-and-upload-files/851326#851326你可以实现你想要的。
另外,请查看这个问题 https://stackoverflow.com/questions/1653469/how-can-i-upload-a-file-and-save-it-to-a-stream-for-further-preview-using-c/1653508#1653508 and 这个建议 http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx关于MVC中的文件上传。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)