【发布时间】:2021-08-01 23:52:55
【问题描述】:
好的,所以我尝试在我的网页上进行文件上传,但是我遇到了Request.Files.Count > 0 始终为 0 并且不会输入 if 语句的问题。我尝试了多种方法,并查看了这个类似问题中的多个答案(有很多),但没有一个解决方案有效。
控制器
public class TicketController : CommonController
{
[HttpPost]
public async Task<ActionResult> Create(TicketViewModel model)
{
if (ValidateModel(model))
{
if (Request.Files.Count > 0) /*This is always 0*/
{
HttpPostedFileBase file = Request.Files[0];
}
}
}
}
查看
@using (Html.BeginForm("Create", "TicketController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-field">
@Html.TextBoxFor(model => model.FileUpload, new { type="file", name = "FileUpload"})
@Html.ValidationMessageFor(model => model.FileUpload)
</div>
}
型号
public class TicketViewModel
{
public HttpPostedFileBase FileUpload { get; set; }
}
尝试添加或删除和更改视图中的名称和模型中的变量。但即使装满,运气也不会总是为零。我的理解是,如果检测到请求键,它会更新变量以实际包含某些内容。所以我的视图和控制器断开了连接,我无法弄清楚。任何方向将不胜感激。
编辑: 提交按钮
<div class="form-group bottom-button-row">
<div class="col-md-offset-2 col-lg-offset-2 col-sm-offset-4">
<div class="col-sm-12 btn-panel">
<div class="float-left">
<input type="button" value="Submit" class="btn btn-primary" data-bind="click:submit,disable:submitting" />
<a role="button" class="btn btn-default" href="@ViewBag.CancelUrl" data-bind="attr:{disabled:submitting}">Cancel</a>
</div>
<div class="loader" data-bind="visible: submitting" style="display: none;"></div>
</div>
</div>
</div>
【问题讨论】:
-
您是否在模型文件上传属性中检查了文件?
-
@dotnetstep 这不会包含任何内容,因为
Request.Files是空的,这就是填充该变量的内容。它甚至没有达到这一点,因为它没有通过Request.Files.Count检查。 -
@dotnetstep 对不起,我想我误解了你原来的问题。一旦我们到达
isValid,我也检查了模型中的变量 FileUpload,它仍然为 NULL。因此,遗憾的是它根本没有填充,但是模型中的其他变量很好,例如电子邮件描述等。所以它只是文件上传不起作用。 -
您尝试的方式有点问题。您的表单有按钮,但它的类型是“按钮”,而不是将其更改为类型 ="submit" 。当您尝试使用 json 发布数据时,这种方法将不起作用,您必须寻找其他插件。
标签: c# asp.net .net asp.net-mvc razor