0

I have a method in web api which i call from the view:

Web api code:

public CarProperties Post(CarProperties car)
{
   if(car.file!=null)
    {
        var path = Path.Combine(Server.MapPath("~/Images/"), Path.GetFileName(car.file.FileName));
        car.file.SaveAs(path);
    }
   new CarRepository().Save(car); //saves the file to database
   return car;
}

model:

public class Car{
    public int Id {get; set;}
    public string Name {get; set;}
    public HttpPostedFileBase file {get; set;}
}

View:

@using(Html.BeginForm("Save", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{

   @Html.TextboxFor(model=>model.file, new { type = "file" })
   @Html.TextboxFor(model=>model.Name)
   <input type="submit" name="Submit" value="Submit"/>
   @Html.ValidationSummary()
}

I get the value of the name in the model but the file is returned as null only.

This same method works if i copy the post method from web api controller to the mvc controller. I cannot understand why it is not working in the web api controller.

Nikitesh
  • 1,287
  • 1
  • 17
  • 38
  • 1
    It doesn't work like that. In your post method you must have model/view model and after that HttpPostedFile: `public CarProperties Post(CarProperties car, HttpPostedFile file)` and name of the HttpPostedFile parameter must be the same as name of the input field – Marcin Feb 24 '15 at 07:22
  • what is your repository process? can you explain? – Shahzad Khan Feb 24 '15 at 07:23
  • @Marcin but i have httpPostedFile in my model, Ill update my question – Nikitesh Feb 24 '15 at 07:26
  • @Rughaani it just saves to database – Nikitesh Feb 24 '15 at 07:27
  • @Html.TextboxFor(model=>model.file, new { type = "file" }) @Html.TextboxFor(model=>model.Name) @Html.ValidationSummary() ,can you use like this? – Shahzad Khan Feb 24 '15 at 07:36
  • Check here: [model binder MVC and web API problems](http://stackoverflow.com/questions/12697310/web-api-model-binder-doesnt-work-with-httppostedfilebase) – Marcin Feb 24 '15 at 07:38
  • That is just the html rendering of what my cshtml code is, what difference does it make?? As in my generated html almost looks the same. – Nikitesh Feb 24 '15 at 07:40
  • @Marcin is that just the option for multipart data? – Nikitesh Feb 24 '15 at 07:42
  • It's describes that WebAPI has problems with binding HttpPostedFileBase and why it works with MVC controller and not with WebAPI. And you can use it for multi part and for one file – Marcin Feb 24 '15 at 07:45

0 Answers0