I\'m going to create profile for my users in ASP.Net MVC application. Users creation controller is something like this:
[HttpPost]
[ValidateAntiForgeryToken]
All i have got, your question is I want to know are there any methods that I can create whole user profile in one form and pass its photo to the same controller (which included photo in UserProfileViewModel)?
Yes. It is possible. If you overwrite the form as Stephen Muecke
said, you should get the photo with viewmodel. If you get null in viewmodel, you can retrieve the file(photo) from the request also.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserProfileViewModel userViewModel)
{
if (ModelState.IsValid)
{
HttpPostedFileBase fileUploadObj= Request.Files[0];
//for collection
HttpFileCollectionBase fileUploadObj= Request.Files;
....
}
return View(userViewModel);
}
Hope this helps :)
File inputs are not sent in the request unless your form element contains the enctype = "multipart/form-data"
attribute. Change the view code to
@using (Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
....
}
You need to use an BeginForm() that allows you to add htmlAttributes, and because you need to add new {enctype = "multipart/form-data" }
@using (Html.BeginForm("UserProfileViewModel ", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UserProfileViewModel(UserProfileViewModel userViewModel)
{
if (ModelState.IsValid)
{
HttpPostedFileBase fileUpload= Request.Files[0];
//for collection
HttpFileCollectionBase fileUpload= Request.Files;
....
}