简体   繁体   English

当我尝试在ASP.NET MVC中上传文件时,它显示为null

[英]When I try to upload a file in ASP.NET MVC, it shows as null

For some reason the paramater OriginalLocation is always null in the following code. 由于某些原因,在以下代码中,参数OriginalLocation始终为null What am I doing wrong? 我究竟做错了什么?

Controller: 控制器:

 [HttpPost]
 public ActionResult File(HttpPostedFileBase OriginalLocation, FileModel model)
 {
     byte[] binaryData = null;
     if (OriginalLocation != null && OriginalLocation.ContentLength > 0)
     {
         binaryData = new byte[OriginalLocation.ContentLength];
         OriginalLocation.InputStream.Read(binaryData, 0,
                          OriginalLocation.ContentLength);
         if (model.UploadFile(OriginalLocation))
         {
             return RedirectToAction("Profile", "Account");
         }
     }
 return View();
 }

View: 视图:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MasterPage.Master" Inherits="System.Web.Mvc.ViewPage<NISE.Web.TestForum.Models.File.FileModel>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
Find upload
</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

<% using (Html.BeginForm("File", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
   { %> 
<%--<form enctype="multipart/form-data" method="post" action="/File/File">--%>

      <input type="file" name="OriginalLocation" id="OriginalLocation"  />

    <input type="submit" value="Upload" />

<%--</form>--%>
<%} %>

</asp:Content>

Model: 模型:

public bool UploadFile(HttpPostedFileBase OriginalLocation)
    {
        if (OriginalLocation != null)
        {
            var filename = Path.GetFileName(OriginalLocation.FileName);
            OriginalLocation.SaveAs(@"C:\" + filename);
            return true;
        }
        return false;
    }

I think you just need to remove the FileModel model parameter from your Action method. 我认为您只需要从Action方法中删除FileModel模型参数即可。 Nothing is being passed to it, and so it's screwing up model binding (unless there is more code in the view that you have deleted from your post). 什么都没有传递给它,因此它搞砸了模型绑定(除非视图中有更多代码已从帖子中删除)。

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

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