1

I have a begin form on a view that contains a file input, but when I try pass the input value to my controller action it returns a null value.

Code in view:

@using (Html.BeginForm("DoCreate", "Admin", FormMethod.Post))
{
    <label>Description:</label>
    @Html.TextBox("Description", null, new { @class = "form-control", @type = "text", required = "required" });
    <label>Price:</label>
    @Html.TextBox("Price", null, new { @class = "form-control", @type = "number", required = "required" });
    <label>Quantity:</label>
    @Html.TextBox("Quantity", null, new { @class = "form-control", @type = "number", required = "required" });
    <label>Image:</label>
    @Html.TextBox("Image", null, new { @class = "form-control", @type = "file", required = "required" });
    <label>Product Type:</label>
    @Html.DropDownList("TypeID", new SelectList(Model, "ID", "TypeName"), "Select Product Type", new { @class = "form-control", required = "required" });

    <button class="btn btn-success" type="submit">Add to Table</button>
}

Code in controller:

[HttpPost]
public ActionResult DoCreate(string Description, float Price, int Quantity, HttpPostedFileBase Image, int TypeID)
{
    return View();
}

If insert a breakpoint by the action, all the other variables have the correct values but the Image returns null, I am not sure why this is, any help would be much appreciated.

1
  • Please add attribute in form enctype="multipart/form-data" Commented Sep 2, 2020 at 11:12

1 Answer 1

2

Please check this

You need to just add htmlAttribute in form new { enctype = "multipart/form-data"}

@using (Html.BeginForm("DoCreate", "Admin", FormMethod.Post,new { enctype = "multipart/form-data" }))
{
    <label>Description:</label>
    @Html.TextBox("Description", null, new { @class = "form-control", @type = "text", required = "required" });
    <label>Price:</label>
    @Html.TextBox("Price", null, new { @class = "form-control", @type = "number", required = "required" });
    <label>Quantity:</label>
    @Html.TextBox("Quantity", null, new { @class = "form-control", @type = "number", required = "required" });
    <label>Image:</label>
    @Html.TextBox("Image", null, new { @class = "form-control", @type = "file", required = "required" });
    <label>Product Type:</label>
    @Html.DropDownList("TypeID", new SelectList(Model, "ID", "TypeName"), "Select Product Type", new { @class = "form-control", required = "required" });

    <button class="btn btn-success" type="submit">Add to Table</button>
}
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.