How to upload/display images using ASP.net MVC4 with Entity Framework

前端 未结 3 1339
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 21:30

I have a data model like so

    public class NewsItem
{
    public virtual int Id { get; set; }
    public virtual string NewsTitle { get; set; }
    public         


        
3条回答
  •  醉梦人生
    2020-12-20 21:57

    I would go like this:

    in your model class:

     public class NewsItem
    {
        public virtual int Id { get; set; }
        public virtual string NewsTitle { get; set; }
        public virtual string NewsContent { get; set; }
        public virtual string NewsImage { get; set; } //string instead of byte because you don't wanna store your whole image file in your database, but just the path of the image, and the image you will store in a folder somewhere on the server
        public virtual DateTime DateAdded { get; set; }
        public virtual bool IsLive { get; set; }
    }
    

    in your controller:

    [Authorize]
        [HttpPost]
        public ActionResult Create(CreateNewsViewModel HttpPostedFileBase file)// add this 
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
                    car.ImagePath = file.FileName;
                }
            // the rest of the code... 
    
            }
            else
            {
                return View(input);
            }
        }
    

    Then in your views you should have:

    for upload:

    
    

    for display in the foreach cycle add:

    @Html.DisplayFor(modelItem => item.NewsImage)
    

    don't forget to add enctype = "multipart/form-data" in the Html.BeginForm

    I hope this would help.

提交回复
热议问题