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

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

问题描述

我有一个问题,当我上传ASP.NET MVC的文件。
我的code是如下:

查看:

  @ {
    ViewBag.Title =指数;
    布局=〜/查看/共享/ _Layout.cshtml
}< H2>索引2< / H>
@using(Html.BeginForm(文件上传,董事会,FormMethod.Post,新{ENCTYPE =的multipart / form-data的}))
{
  <输入类型=文件/>
  <输入类型=提交/>
}

控制器:

  [HttpPost]
公众的ActionResult文件上传(HttpPostedFileBase uploadFile)
{
    如果(uploadFile =空&放大器;!&放大器; uploadFile.ContentLength大于0)
    {
        字符串文件路径= Path.Combine(使用Server.Mappath(/ temp的),Path.GetFileName(uploadFile.FileName));
        uploadFile.SaveAs(文件路径);
    }
    返回查看();
}

但uploadFile始终返回null。
任何人都可以弄清楚为什么?


解决方案

  @ {
    ViewBag.Title =指数;
    布局=〜/查看/共享/ _Layout.cshtml
}< H2>索引2< / H>
@using(Html.BeginForm(文件上传,董事会,FormMethod.Post,新{ENCTYPE =的multipart / form-data的}))
{
  <输入类型=文件名称=一个UploadFile/>
  <输入类型=提交/>
}

你必须为了在ASP.net MVC模型绑定工作提供的名称输入类型文件uploadFile 并同时结果确保您输入类型的文件名,参数名称 HttpPostedFileBase 是相同的。

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

View:

@{
    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" />
}

Controller:

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

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" />
}

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天全站免登陆