Im trying to pass the filepath into my ProfileViewModel but it seems to stay Null even thought the other values are filled.

I have tried debugging it but cant seem to find where its going wrong.

My view

@using (Html.BeginForm("EditProfile", "Profile", FormMethod.Post))
{
    @Html.AntiForgeryToken()

        @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
        <input asp-for="Photo" type="file"/><br />

        <div class="form-group"> 
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>

my controller

        public IActionResult profile()
        {
            return View();
        }

        private readonly IHostingEnvironment he;
        public ProfileController(IHostingEnvironment e)
        {
            he = e;
        }

        [HttpPost]
        public ActionResult EditProfile(ProfileViewModel profile)
        {
            string ID = Request.Cookies["UserID"];
            if (ModelState.IsValid)
            {
                var Photo = profile.Photo;
                var FileName = Path.Combine(he.WebRootPath, Path.GetFileName(Photo.FileName));
                if (logicprofile.logicEditProfile(profile.BIO, profile.Sex, profile.Preffered, FileName, Convert.ToInt32(ID)) == true)
                {
                    profile.Photo.CopyTo(new FileStream(FileName, FileMode.Create));
                    ViewBag.Message = "Profile Updated";
                    return View("profile", profile);
                }
                else
                {
                    ViewBag.Message = "Something went wrong";
                    return View("profile", profile);
                }
            }
            else
            {
                return View("profile", profile);
            }


        }

ViewModel

[DisplayName("A picture of you!")]
public IFormFile Photo { get; set; }

I expect my pictures to be saved in a folder and the path to a database so I can use them as profile pictures.

2 Answers

0
Dilip On Best Solutions

You should use enctype in form for passing file type data.

@using (Html.BeginForm("EditProfile", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))
0
Community On

You need to add multipart/form-data in your view something like

<form id="form1" method="post" asp-controller="Demo" asp-action="Register" enctype="multipart/form-data">

And make sure your Photo model is look like this

public IFormFile Photo { get; set; }