Upload Images while creating new Model

前端 未结 3 807
孤独总比滥情好
孤独总比滥情好 2020-12-21 10:50

I\'m going to create profile for my users in ASP.Net MVC application. Users creation controller is something like this:

[HttpPost]
[ValidateAntiForgeryToken]         


        
相关标签:
3条回答
  • 2020-12-21 10:57

    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 :)

    0 讨论(0)
  • 2020-12-21 11:12

    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" }))
    {
        ....
    }
    
    0 讨论(0)
  • 2020-12-21 11:15

    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;
     ....
     }
    
    0 讨论(0)
提交回复
热议问题