HttpPostedFileBase 在 ASP.NET MVC 中总是返回 null [英] HttpPostedFileBase always return null in ASP.NET MVC

查看:32
本文介绍了HttpPostedFileBase 在 ASP.NET MVC 中总是返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET MVC 中上传文件时遇到问题.我的代码如下:

I have a problem when I upload a file in ASP.NET MVC. My code is below:

查看:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index2</h2>
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <input type="file" />
  <input type="submit" />
}

控制器:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
    if (uploadFile != null && uploadFile.ContentLength > 0)
    {
        string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName));
        uploadFile.SaveAs(filePath);
    }
    return View();
}

但是uploadFile 总是返回null.谁能找出原因??

But uploadFile always returns null. Can anyone figure out why??

推荐答案

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index2</h2>
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <input type="file" name="uploadFile"/>
  <input type="submit" />
}

您必须提供输入类型文件的名称以上传文件,以便在 ASP.net mvc 中进行模型绑定工作,并且
还要确保输入类型文件的名称和HttpPostedFileBase 的参数名称是相同的.

you have to provide name to input type file to uploadFile in order to model binding work in ASP.net mvc and
also make sure that name of your input type file and argument name of HttpPostedFileBase is identical.

这篇关于HttpPostedFileBase 在 ASP.NET MVC 中总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆