Reputation: 872
I have the following MVC form and controller to upload an image for merchandise with a given id. The id is null when this form is submitted to the controller for some reason. I checked in the rendered HTML and the correct ID is being rendered on the webpage.
The form:
@using(Html.BeginForm(new{id = ViewBag.id})){
<input type="hidden" name="id" id="id" value="@ViewBag.Id"/>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
}
And the controller:
[HttpPost]
public ActionResult AddImage(int merchandiseId, HttpPostedFileBase image)
<snip>
Why would submitting this form cause merchandiseId to be null?
Upvotes: 1
Views: 1484
Reputation: 14292
Change the Html.BeginForm
like below :
@using(Html.BeginForm(new{merchandiseId = ViewBag.id}))
This will fix your problem.
Upvotes: 0
Reputation: 56853
merchandiseId
would be 0 (and not null) because there is no input on your form called merchandiseId
.
<input type="hidden" name="merchandiseId" id="merchandiseId" value="@ViewBag.Id"/>
Upvotes: 1
Reputation: 7445
Becouse you use wrong names. Change
<input type="hidden" name="id" id="id" value="@ViewBag.Id"/>
to
<input type="hidden" name="merchandiseId" id="id" value="@ViewBag.Id"/>
or
public ActionResult AddImage(int merchandiseId, HttpPostedFileBase image)
to
public ActionResult AddImage(int id, HttpPostedFileBase image)
Upvotes: 3