1

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?

0

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.