Why images paths not store in database MVC5?

Abeer S 41 Reputation points
2022-04-19T09:36:20.977+00:00

I'm new to MVC so I hope to get help regarding my question. I am making users upload images. the image path will store in the database but the image itself will store in the Content folder. The code is working fine (which means there is no error) but I don't get the wanted result. I appreciate your help. Thanks in advance.

Here is the Controller code:

[HttpPost]  
        [ValidateAntiForgeryToken]  
        public ActionResult Create([Bind(Include = "EmployeeId,EmpName,EmpEmail,Poition,Nationality,Last_W_D,EmpHOD,Password,DepId,SignaturePath,DoctorCategory")] Tbl_Employee tbl_Employee, HttpPostedFileBase file)  
        {  
            if (ModelState.IsValid)  
            {  
                if(file != null)  
                {  
                    file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/Employees/") + file.FileName);  
                    tbl_Employee.SignaturePath = file.FileName;  
                }  
                db.Tbl_Employee.Add(tbl_Employee);  
                db.SaveChanges();  
                return RedirectToAction("Index");  
            }  

Here is the "Create view " code:

@model ClearanceFirst.Models.Tbl_Employee  
  
@{  
    ViewBag.Title = "Create";  
}  
  
<h2>Create</h2>  
  
  
@using (Html.BeginForm("Create", "Tbl_Employee", null, FormMethod.Post, new { enctype = " multipart/form-data" }))  
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
        <h4>Tbl_Employee</h4>  
        <hr />  
<div class="form-group">  
            @Html.LabelFor(model => model.SignaturePath, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                <input id="signaturePath " title ="upload images " type="file" name="file" />  
               @Html.ValidationMessageFor(model => model.SignaturePath, "", new { @class = "text-danger" })   
            </div>  
        </div>  

Here is the "Index view" code:

<td>
@if (!string.IsNullOrWhiteSpace(item.SignaturePath))
{
<img width = "70" height = "50"
src="~/Content/Images/Employees/@URL .Content(item.SignaturePath)"
alt= "Alternate Text"/> }
</td>

Developer technologies | ASP.NET | Other
SQL Server | Other
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2022-04-20T09:03:16.167+00:00

    Hi @Abeer S ,
    I tried your code and found the problem, your file is always empty, so the code doesn't execute the statement in the if.
    194605-9.jpg
    I wrote a demo according to your needs, you can refer to it.
    Controller

    public class HomeController : Controller  
        {  
            private EmpContext db = new EmpContext();  
            public ActionResult Index()  
            {  
                return View();  
            }  
            public ActionResult Create()  
            {  
                return View();  
            }  
            [HttpPost]  
            [ValidateAntiForgeryToken]  
            public ActionResult Create(Tbl_Employee tbl_Employee)  
            {  
                if (ModelState.IsValid)  
                {  
                    if (Request.Files.Count > 0)  
                    {  
                        HttpPostedFileBase file = Request.Files[0];  
                        if (file.ContentLength > 0)  
                        {  
                            var fileName = Path.GetFileName(file.FileName);  
                            tbl_Employee.SignaturePath = Path.Combine(  
                                Server.MapPath("~/Upload"), fileName);  
                            file.SaveAs(tbl_Employee.SignaturePath);  
                        }  
                        db.Tbl_Employee.Add(tbl_Employee);  
                        db.SaveChanges();  
                        return RedirectToAction("Index");  
                    }  
                }  
      
                return View(tbl_Employee);  
            }  
        }  
    

    cshtml

    @model  ContosoUniversity.Models.Tbl_Employee  
    @{  
        ViewBag.Title = "Create";  
    }  
    <h2>Create</h2>      
    @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
    {  
        @Html.AntiForgeryToken()  
      
        <div class="editor-field">  
            @Html.TextBoxFor(model => model.SignaturePath, new { type = "file" })  
            @Html.ValidationMessageFor(model => model.SignaturePath)  
      
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-primary" />  
            </div>  
        </div>  
    }  
    

    194642-9.gif
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Abeer S 41 Reputation points
    2022-04-20T08:40:46.697+00:00

    Hi AgaveJoe,

    Thank you so much for your reply. I explained below and I hope is clear.

    "explain the wanted results and what actually happens"

    There are 2 views:

    1- Index: which displays information about the employees.

    Here is the code related to SignaturePath:

    <td>  
                @if (!string.IsNullOrWhiteSpace(item.SignaturePath))  
                {  
                    <img width = "70" height = "50"  
                         src="~/Content/Images/Employees/@Url.Content(item.SignaturePath)"  
                         alt= "Alternate Text"/>  
      
                }  
    </td>  
    

    194538-capture.jpg

    2- Create: when the user click on Create New, the view " Create" open which let the user fill out the form. one of the fields is SignaturePath which make the user to upload the image from his machine. that image will store in database as the path but the image itself will be stored in the server inside Content/Images/Employees. So I wrote that code in the Controller to point out to the image in the server

    file.SaveAs(HttpContext.Server.MapPath("~/Content/Images/Employees/") + file.FileName);  
                        tbl_Employee.SignaturePath = file.FileName;  
    

    194490-capture1.jpg

    Also take a look at the database table to see what data is stored

    in database, the SignaturePath is Null

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.