miechooy
miechooy

Reputation: 3422

Passing Image to Controller ASP.NET MVC

I am trying to send Image and ImageName from View to Controller.

Here's how my controller looks:

  [HttpPost]
  public ActionResult Add(BoxAddViewModel image)
  {
      //TODO: Add new box
      return RedirectToAction("Index");
  }

This is the model:

 public class BoxAddViewModel : BaseViewModel
 {
     public int Id { get; set; }
     [Required]
     [DisplayName("Name")]
     public string Name { get; set; }
     [Required]
     [DisplayName("Source")]
     public HttpPostedFileBase Source { get; set; }

 }

And finally the view:

@using (Html.BeginForm("Add", "BoxManagement", new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{

    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "col-sm-2 control-label" })
        <div class="col-sm-10">
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @name = "Name"})
            @Html.ValidationMessageFor(m => m.Name)
        </div>
        @Html.LabelFor(m => m.Source, new { @class = "col-sm-2 control-label" })
        <div class="col-sm-10">
            <!--Html.TextBoxFor(m => m.Source, new { type = "file",}) -->
            @Html.ValidationMessageFor(m => m.Source)
            <input type="file" name="Source" id="Source" />
        </div>
    </div>
    <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span>Add</button>
    @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
}

It comes into the Add method and the Name property value is correct but the Source is null.

Anyone know how to solve this?

Upvotes: 1

Views: 1202

Answers (1)

user3559349
user3559349

Reputation:

Your using the wrong overload of BeginForm() and adding route values, not html attributes (always inspect the html your generating). Use

@using (Html.BeginForm("Add", "BoxManagement", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))

Side note: Remove new { @name = "Name"} from your TextBoxFor() method. Never attempt to override the name attribute generated by the HtmlHelper methods unless you want binding to fail (and is this case it does nothing anyway)

Upvotes: 2

Related Questions