I have a form that I'm posting 2 different files that belongs to 2 different values in my Db table.
Eg. file1=user image
, file2=user company logo
.
So I need to attach the files url to it's db value with my viewModel
,
something like this:(Will never work)
public ActionResult Create(LectureFormViewModel viewModel)
{
foreach ((string item in Request.Files).viewModel.Image1)
{
//Do
}
foreach ((string item in Request.Files).viewModel.Image2)
{
//Do
}
var lecture = new Lecture
{
Image1 = xxx,
Image2=yyy,
}
_context.LectureGigs.Add(Lecture);
}
My ViewModel (I have remove parameters )
public class LectureFormViewModel
{
public int Id { get; set; }
public byte Genre { get; set; }
public IEnumerable<Genre> Genres { get; set; }
public string Image1 { get; set; }
public string Image2 { get; set; }
public string Action
{
get
{
Expression<Func<LecController, ActionResult>>
update = (c => c.Update(this));
Expression<Func<LecController, ActionResult>>
create = (c => c.Create(this));
var action = (Id != 0) ? update : create;
return (action.Body as MethodCallExpression).Method.Name;
}
}
}
The form(View)
@using VoosUpW.Models
@model VoosUpW.ViewModels.LectureFormViewModel
@using (Html.BeginForm(Model.Action, "Lec", FormMethod.Post, new { enctype = "multipart/form-data", @id = "abcdefg" }))
{
//parm
<div class="form-group">
@Html.LabelFor(f => f.Image1)
<i class="glyphicon glyphicon-folder-open"></i>
<input id="Image1" name="Image" type="file" class="">
</div>
<div class="form-group">
@Html.LabelFor(f => f.Image2) <i class="glyphicon glyphicon-folder-open"></i>
<input type="file" name="Image2" class="btn btn-default btn-sm btn-google btn-group-justified hvr-shadow " />
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
}
my action header
public ActionResult Create(LectureFormViewModel viewModel)
{
You can do this easily with the below code using
IEnumerable<HttpPostedFileBase>
:Product:
The action:
Note: Don't worry about image path. For the ease, just save the file name in the Db and finally to display in the view, do the following and for the image upload, the code you showed will work: