sitBy
sitBy

Reputation: 269

MVC Pass element id from view to controller

foreach (var item in Model)
{
    using (Html.BeginForm("PreviewImage", "Music", FormMethod.Post, new { @enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

        <input type="file" class="upload-image" id="[email protected]" name="file" accept="image/*">
        <button class="btn btn-default" id="[email protected]" style="display: none" type="submit"></button>
    }
}

How do I pass the file id to the controller?

Upvotes: 0

Views: 1417

Answers (1)

Logan B. Lehman
Logan B. Lehman

Reputation: 5007

Under the assumption that you want to pass back the path of the image uploaded - Inside of your controller, use the following:

if (Request.Files.Count > 0)
{
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var serverPath = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(serverPath);

         }
}

Under the assumption that you are talking about the @item.Id variable you are appending the Id, I would add @item.Id here:

using (Html.BeginForm("PreviewImage", "Music", FormMethod.Post, new { @enctype = "multipart/form-data", @itemId = @item.Id }))

And then make the corresponding changes to your controller.

Upvotes: 1

Related Questions