ASP.NET MVC传递模型* *一起用文件传回控制器

编程入门 行业动态 更新时间:2024-10-27 15:30:24
本文介绍了ASP.NET MVC传递模型* *一起用文件传回控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好吧,我已经在这个持续了几个小时,我根本无法找到解决方案。

Ok, I've been going at this for several hours and I simply cannot find the solution.

我想从我的用户获取一些数据。因此,首先,我用一个控制器来创建一个接收模型的视图:

I want to get some data from my user. So first, I use a controller to create a view which receives a Model:

public ViewResult CreateArticle() { Article newArticle = new Article(); ImagesUploadModel dataFromUser = new ImagesUploadModel(newArticle); return View(dataFromUser); }

然后,我的观点:

Then, I have the view:

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

和最后 - 原始控制器,但这次配置为接受数据

and finally - the original controller, but this time configured to accept the data:

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

该控制器的其余部分,因为没有不管我做什么,在计数属性 Request.Files (或 Request.Files.Keys )保持为0。我根本无法找到一个方法来从表单传递文件(模型通过就好了)。

The rest of this controller does not matter since no matter what I do, the count attribute of Request.Files (or Request.Files.Keys) remains 0. I simply can't find a way to pass the files from the form (the Model passes just fine).

推荐答案

您可能要考虑不与形式 - 其余张贴文件有good原因等方式你可以达到你想要的东西。

You might want to consider not posting the files with the rest of the form- there are good reasons and other ways you can achieve what you want.

此外,检查this问题和这条建议在关于MVC文件上传

Also, check out this question and this advice regarding file uploads in MVC.

更多推荐

ASP.NET MVC传递模型* *一起用文件传回控制器

本文发布于:2023-11-16 07:08:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602095.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   模型   文件   ASP   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!