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>
    }
6
  • To store strings you can use varchar or nvarchar types in your database Commented Apr 16, 2019 at 23:17
  • Or is that not your question? It's unclear. What actual problem are you experiencing with the code above? Commented Apr 16, 2019 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 ? Commented Apr 16, 2019 at 23:58
  • You got it @ADyson ? Commented Apr 17, 2019 at 0: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. Commented Apr 17, 2019 at 5:32

1 Answer 1

2

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" /> 
Sign up to request clarification or add additional context in comments.

9 Comments

I did it and also answer is so logical but although i add a photo in from form area , userImageUrl column in MsSQL is Null. Creating is succesful but while sending file , ı am facing Null area. What might be problem ?
did you debug that user.userImageUrl has value?
file.FileName gives an error like file.FileName = 'file.FileName' threw an exception of type 'System.NullReferenceException' when i examine with break point. It should be wrong method.
did you move user.userImageUrl = "~/User_Images/" + file.FileName; inside if(file !=null && file.ContentLength > 0) ?
Can you change <input type="file" name="ImageFile" /> to <input type="file" name="file" /> ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.