繁体   English   中英

文件上传在ASP.NET MVC4 - 移动模板中不起作用

[英]file upload doesn't work in ASP.NET MVC4 - mobile template

我使用C#和ASP.NET MVC4作为Web应用程序(移动模板)。

现在我在视图中有以下代码:

     @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
     { 
     <label for="file">Upload:</label>
     <input type="file" name="file" id="file"/>
     <input type="submit" value="Upload" />
     }

这在我的控制器中:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string path = System.IO.Path.Combine(Server.MapPath("~/Content"), System.IO.Path.GetFileName(file.FileName));
        file.SaveAs(path);
        ViewBag.Message = "File uploaded successfully";
        return View();
    }

当我运行应用程序并尝试上传文件时,我得到“对象引用未设置为对象的实例”。 Visual Studio中的消息。 但我知道上面的代码在ASP.NET MVC3中工作正常,因为我之前使用过它。

谁能帮我这个?

将此属性添加到表单: data-ajax="false"

@using(Html.BeginForm("Index", "Home", FormMethod.Post,  new { enctype="multipart/form-data", data_ajax="false"})){
     <label for="file">Upload:</label>
     <input type="file" name="file" id="file"/>
     <input type="submit" value="Upload" />
}

您不必使用HttpPostedFileBase ,因为事实上您不必在[HttpPost] Action中接收任何参数。 只要表单设置为enctype = "multipart/form-data" (您已经这样做),就可以从请求中获取文件:

var file = Request.Files[0];

暂无
暂无

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

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