C# 我得到的错误是;用户代码“未处理NullReferenceException”;当我尝试上传图片时,ASP.NET MVC 4

C# 我得到的错误是;用户代码“未处理NullReferenceException”;当我尝试上传图片时,ASP.NET MVC 4,c#,asp.net,asp.net-mvc,asp.net-mvc-4,c#-4.0,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,C# 4.0,控制器 [HttpPost] public ActionResult Index(Add_Book _books) { BusinessLayer booksBusinessLayer = new BusinessLayer(); //books file = new books(); //var book = new books(); 线下接收错误 模态 public class books { public s

控制器

    [HttpPost]
    public ActionResult Index(Add_Book _books)
    {
        BusinessLayer booksBusinessLayer = new BusinessLayer();
        //books file = new books();
        //var book = new books();
线下接收错误

模态

public class books
{
    public string ID
    {
        get;
        set;
    }

    public string ISBN
    {
        get;
        set;
    }

    public string Book_Title
    {
        get;
        set;
    }

    public string Book_Cat
    {
        get;
        set;
    }

    public string Language
    {
        get;
        set;
    }

    public string Book_Desc
    {
        get;
        set;
    }

    public string Price
    {
        get;
        set;
    }

    public string Book_Img
    {
        get;
        set;
    }

    public HttpPostedFileBase File
    {
        get;
        set;
    }

    public int Qty
    {
        get;
        set;
    }

    public int Qty_Alert
    {
        get;
        set;
    }
 }

请提供解决方案。

如David Tansey所说,\u books.File.FileName假定该值不为null,因此您需要在尝试访问该对象之前进行验证

当我使用上传文件时,我做了如下代码,希望这对你有帮助

只是在你的视野中使用

   <input type="file" />

异常发生的位置可能重复-这可能会让您了解哪些值设置为null。您对
\u books.File.FileName
的引用假定
\u books.File
不为null。在引用
FileName
   <input type="file" />
   [HttpPost]
    public ActionResult SaveFile(YourModel model)
    {
        foreach (string file in Request.Files)
        {
           SaveYourFile(Request.Files[file]);
        }
    return View();
    } 

     private void SaveYourFile(HttpPostedFileBase file)
     {
       if(file.ContentLenght >0)
         {
           //now you can access to your uploaded file
          var book = new books();
        var path = Path.Combine(Server.MapPath("~/Osho_Images"), file.fileName);
         book.File.SaveAs(path);

          booksBusinessLayer.AddBooks(_books);
         }
     }