0

I'm new to ASP.NET and i'd be so grateful if someone could help. I have my file input:

<form action="NewProject.cshtml" method="post" enctype="multipart/form-data">
<fieldset>
  <legend> Upload Image </legend>
  <label for="Image">Image</label>
  <input type="file" name="Image" id ="filename"/>
  <br/>
  <input type="submit" value="Upload" id="Add" />
</fieldset>

To upload image i use:

@{  WebImage photo = null;
var newFileName = "";
var imagePath = "";

if(IsPost){
    photo = WebImage.GetImageFromRequest();
    if(photo != null){
        newFileName = Guid.NewGuid().ToString() + "_" +
            Path.GetFileName(photo.FileName);
        imagePath = @"Images\" + newFileName;

        photo.Save(@"~\" + imagePath);
//an attempt
       PoleInvestProject.Models.Project project = new PoleInvestProject.Models.Project();
            project.Image = imagePath; //storing in model property Image

        }
    }
}

And now i need to get the path of the image from there and associate it with my model, which has the property public string Image { get; set; }. I want to store this file path in my database by DBContext context.

  context.Projects.Add(new Project()
            {

                Image = model.Image

            });
            context.SaveChanges();

But this gives me NULL, there's nothing in my database table for Projects. What am I doing wrong? Thanks in advance!

Gyuzal
  • 1,581
  • 10
  • 52
  • 99
  • Is that business logic in your view? Don't do that. A great place to start is http://www.asp.net/mvc. Then take a look at http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0. – jrummell Feb 28 '13 at 18:32
  • The first two sections of code are in view, the third- in a controller's action. Thanks for the link! – Gyuzal Feb 28 '13 at 18:50

1 Answers1

0

create a new property in your model by value of string and call it FileName. Now in your view, create a hidden filed with the same name

<input type="hidden" id="FileName" value="" />

Add a change handle to the file input

<input type="file" onchange="document.getElementById('FileName').value = this.value;" />

This should update the hidden filed with the value of the file name every time you change it. When you do your postback, the model binder will do the rest and you will have the name of the file in model.FileName

Hope this helps

Chintana Meegamarachchi
  • 1,798
  • 1
  • 12
  • 10
  • And as jrummell pointed out, try to keep the view neutral from business logic. Try to create a view model and a service layer and delegate the biz-logic to the service layer. In your case, ideally you should also have a data access layer as well. A well architected solution will surely payback on the long run - cheers – Chintana Meegamarachchi Mar 01 '13 at 00:29