-2

Controler

    [HttpPost]
    public ActionResult Index(Add_Book _books)
    {
        BusinessLayer booksBusinessLayer = new BusinessLayer();
        //books file = new books();
        //var book = new books();

receiving error at below line

        var fileName = Path.GetFileName(_books.File.FileName);
        //var fileName = book.File.FileName;
        var path = Path.Combine(Server.MapPath("~/Osho_Images"), fileName);
        book.File.SaveAs(path);

        booksBusinessLayer.AddBooks(_books);

        return View();
    }

Modal

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;
    }
 }

Pleas provide the solution.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Mayank Bhuvnesh
  • 135
  • 1
  • 4
  • 14
  • 4
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Brad C Jul 01 '15 at 15:36
  • Where does the exception occur - that will probably give you an idea of what value is set to null. – PaulF Jul 01 '15 at 15:40
  • 2
    Your reference to `_books.File.FileName` assumes that `_books.File` is NOT NULL. You should test this first befire referencing `FileName` – David Tansey Jul 01 '15 at 15:41

1 Answers1

0

Like David Tansey say, _books.File.FileName assume that is NOT null, so you need to validate before to try get access to the object,

When I worked with upload files I did something like the following code, hope this help you

just use in your view

   <input type="file" />

then in your controller, in this case i put the for, because the user can upload multiple files,

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