1

I am trying to submit a form containing a file upload using c# ASP MVC with Entity. My problem is that the file is always null.

The view :

@model Com.Work.With.Me.Models.ObjVM
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
<form id="formObj" action="AddMe">
    <input type="file" id="objPdfFile" name="Obj.PdfFile" />
    </select>
    <input type="text" id="objName" name="Obj.Name" />
</form>

The viewmodel :

public class ObjVM
{
    public string Name{ get; set; }
    public HttpPostedFileBase PdfFile{ get; set; }
    public ObjVM()
    {
    }
}

The controller :

public ActionResult AddMe(ObjVM obj)
{
    //her obj.Name is fine
    //but obj.PdfFile is null
    return View();
}

Any ideas?

jBravo
  • 873
  • 1
  • 9
  • 28
  • 1
    Have you set the `enctype` in the header to `multipart/form-data` and encoded the content in that manner? (https://stackoverflow.com/a/4526286/1838819). This also needs to be a HTTP `POST` both on the client side and the action needs to be marked with `[HttpPost]` – DiskJunky Oct 09 '17 at 15:36
  • You are right ! – jBravo Oct 09 '17 at 15:50
  • Why did you say "without Razor" in your title? You are clearly using Razor. – mason Oct 09 '17 at 16:57

2 Answers2

1

Thanks to @DiskJunky, I corrected my form adding method="post" enctype="multipart/form-data":

<form id="formObj" action="AddMe" method="post" enctype="multipart/form-data">
    <input type="file" id="objPdfFile" name="Obj.PdfFile" />
    </select>
    <input type="text" id="objName" name="Obj.Name" />
</form>

And my controller adding [HttpPost] :

[HttpPost] 
public ActionResult AddMe(ObjVM obj)
{
    //obj.PdfFile is not null anymore !
    return View();
}
jBravo
  • 873
  • 1
  • 9
  • 28
  • But remove the pointless `value="@Model.PdfFile"` - you cannot set the value of a file input (the only way it can be set is by the user selecting a file in the browser). And it can be just `name="PdfFile"` (and `name="Name"` for the textbox) –  Oct 09 '17 at 21:47
  • And you are using razor anyway (what do you think the `@` is). So why not do it properly and strongly bind to your model using the `HtmlHelper` methods. –  Oct 09 '17 at 21:48
  • @StephenMuecke Yes, you're right. It's just that the syntax of razor's form bears its name. It is such a pain! I prefer to avoid it as much as possible. – jBravo Oct 10 '17 at 07:57
  • Why would you not want all the built in features such as strongly typed 2-way model binding, client side validation etc. To not use the `HtmlHelper` methods is just crazy –  Oct 10 '17 at 08:01
0
Add Your Ui to this Code `enctype = "multipart/form-data"` Code

@using (Html.BeginForm("Action Name", "Control Name", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    <input type="file" id="objPdfFile" value="@Model.PdfFile" name="Obj.PdfFile" />
        </select>
        <input type="text" id="objName" value="@Model.Name" name="Obj.Name" />
    }
Kasunjith Bimal
  • 168
  • 1
  • 12