简体   繁体   English

文件上传 ASP.NET MVC 不起作用

[英]File Upload ASP.NET MVC Not Working

I have tried my best however HttpPostedFileBase filee is always null我已经尽力了,但是HttpPostedFileBase filee总是为null

Controller Action控制器动作

 public ActionResult UploadFile(HttpPostedFileBase filee)
        {
            try
            {
                if (filee.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(filee.FileName);
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
                    filee.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }

Razor View剃刀视图

@{
    ViewBag.Title = "UploadFile";
}

<h2>UploadFile</h2>

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <div>
        @Html.TextBox("file", "", new { type = "file" }) <br />
        <input type="submit" value="Upload" />

        @ViewBag.Message

    </div>


}  

public ActionResult UploadFile(HttpPostedFileBase filee)的参数名称更改为public ActionResult UploadFile(HttpPostedFileBase file)或将输入名称@Html.TextBox("file", "", new { type = "file" })更改为@Html.TextBox("filee", "", new { type = "file" })

You have to use same name of yor input field as your HttpPostedFileBase object name while you are working on loosly type view !在处理松散类型视图时,您必须使用与 HttpPostedFileBase 对象名称相同的输入字段名称!

Example :例子 :

    @{
        ViewBag.Title = "UploadFile";
    }

    <h2>UploadFile</h2>

    @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {

        <div>
            @Html.TextBox("filee", "", new { type = "file" }) <br />
            <input type="submit" value="Upload" />

            @ViewBag.Message

        </div>

}  

Or If you don't want to use same names ?或者如果您不想使用相同的名称? you just have to use a tightly coupled view type view你只需要使用一个紧密耦合的视图类型视图

Tightly紧紧
Example:例子:

@model PROJECTNAME.Models.MODELNAME

        @{
            ViewBag.Title = "UploadFile";
        }

        <h2>UploadFile</h2>

        @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {

            <div>
                @Html.TextBox(model => model.YOURCOLUMNNAME , "", new { type = "file" }) <br />
                <input type="submit" value="Upload" />

                @ViewBag.Message

            </div>

    }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM