1

I am a student developer in .Net MVC 5 and I want to insert image from new user to my database. I found a lot of method for byte[] data type but according to my researchs , there is no source for string data type.(Example; Entity Framework 5 Code first adding an image) . What can i do for string column of ImageUrl in my database? Could you help me at this issue ?

My Model :

public class usersModel{
public string userImageUrl{get;set;}
}

My Controller :

 public class UsersController : Controller
    {
        AgmEntities db = new AgmEntities();

        public ActionResult Create()
        {
            return View("Create", new usersModel());
        }

        [HttpPost]
        public ActionResult Create(usersModel uModel,HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {

                return View("Create");
            }

            var user = new Users();

            if(file !=null && file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string imgPath = Path.Combine(Server.MapPath("~/User_Images/"), fileName);
                file.SaveAs(imgPath);
            }
            user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
            db.Users.Add(user);
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
    }

My cshtml :

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

        <div class="form-group">
            @Html.LabelFor(model => model.userImageUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="ImageFile" />
                @Html.ValidationMessageFor(model => model.userImageUrl, "", new { @class = "text-danger" })
            </div>
        </div>
    }
ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Emre Sert
  • 318
  • 6
  • 19
  • To store strings you can use `varchar` or `nvarchar` types in your database – ADyson Apr 16 '19 at 23:17
  • Or is that not your question? It's unclear. What actual problem are you experiencing with the code above? – ADyson Apr 16 '19 at 23:18
  • I mean my method is working exactly but i can't save image file as url to my database column. I am facing an error on this line `user.userImageUrl = "~/User_Images/" + file.FileName;` while inserting. Is it clear now ? – Emre Sert Apr 16 '19 at 23:58
  • You got it @ADyson ? – Emre Sert Apr 17 '19 at 00:00
  • "can't" isn't an error message or problem statement that anyone can fix. What happens when you do this? An error? Unexpected outcome? Please be clear and specific about the issue. I think the answer below is probably correct but it would be easier for everyone if you give a more exact description of what happens in your code. – ADyson Apr 17 '19 at 05:32
  • When i ask a question from here , i will be more careful to your advice. – Emre Sert Apr 17 '19 at 12:20

1 Answers1

3

You must add new { enctype="multipart/form-data"} to your form to allow upload file.

Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})

Change cshtml code to:

@using (Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})) 
{
    @Html.AntiForgeryToken()

        <div class="form-group">
            @Html.LabelFor(model => model.userImageUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="ImageFile" />
                @Html.ValidationMessageFor(model => model.userImageUrl, "", new { @class = "text-danger" })
            </div>
        </div>
    }

and move this line of code inside if user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/ in this case file.FileName may be null.

 if(file !=null && file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string imgPath = Path.Combine(Server.MapPath("~/User_Images/"), fileName);
                file.SaveAs(imgPath);
                user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
            }

One more note that need change parameter name in action same as name of input type file:

<input type="file" name="ImageFile" /> to <input type="file" name="file" /> 
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62