views:

56

answers:

2

When I select a file and submit the file for upload, I can't get the value of the File path in my Model. In the Controller it shows as null. What am I doing wrong?

View

<form method="post" action="/Account/Profile" enctype="multipart/form-data">
    <label>Load photo: </label>
    <input type="file" name="filePath" id="file" />
    <input type="submit" value="submit" />
</form>

Controller

public ActionResult Profile(ProfileModel model, FormCollection form)
{
    string path = Convert.ToString(model.FilePath);
    return View();
}

Model

public HttpPostedFileBase FilePath
{
    get
    {
        return _filePath;
    }
    set
    {
        _filePath = value;
    }
}

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

I don't have VS to simulate your problem. So im not sure bout the answer.

Try this, might work

<input type="file" name="model.FilePath" id="file" />

If not work then, Try look it on your formcollection & HttpContext.Request.Files

It should be there.

happy
doesnt work :((
Ragims
happy
A: 

I don't think model binding works with HttpPostedFileBase...

It should work if you take it out of your ViewModel and do it like this:

public ActionResult Profile(HttpPostedFileBase filePath)
{
    string path = Convert.ToString(filePath);
    return View();
}

HTHs,
Charles

Ps. This post could help explain things: ASP.NET MVC posted file model binding when parameter is Model

Charlino