2017-08-06 120 views
0

我想将图像插入到图像文件夹,并使用实体模型framework.My是添加图像路径进入数据库中的数据库,插入图像路径到MVC

public class Orphan 
    { 
     public int Id { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public int Age { get; set; } 
     public string Gender { get; set; } 
     public bool Disable { get; set; } 
     public DateTime JoinedDate { get; set; } 
     public DateTime? LeaveDate { get; set; } 
     public Carer Carer { get; set; } 
     public string CarerName { get; set; } 
     public string ImagePath { get; set; } 


    } 

这是视图模型,

public partial class OrphanViewModel 
     { 
      [Required] 
      [DisplayName("First Name")] 
      public string FirstName { get; set; } 
      [Required] 
      [DisplayName("Last Name")] 
      public string LastName { get; set; } 
      [Required] 
      public int Age { get; set; } 
      [Required] 
      public string Gender { get; set; } 
      [Required] 
      public bool Disable { get; set; } 
      [Required] 
      public string CarerName { get; set; } 
      public string ImagePath { get; set; } 
      public HttpPostedFileBase ImageFile { get; set; } 
     } 

这是图像路径的视图。

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

这里是控制器

[HttpPost] 
[ValidateAntiForgeryToken] 
     public ActionResult Create(OrphanViewModel ovm) 
     { 
      string fileName = Path.GetFileNameWithoutExtension(ovm.ImageFile.FileName);   

string extension = Path.GetExtension(ovm.ImageFile.FileName); 
      fileName = fileName + DateTime.Now.ToString("yymmssff") + extension; 
      ovm.ImagePath = "~/Image/" + fileName; 
      fileName = Path.Combine(Server.MapPath("~/Image/"), fileName); 
      ovm.ImageFile.SaveAs(fileName); 

      if (ModelState.IsValid) 
      { 
       db.Orphans.Add(new Orphan() 
       { 
        FirstName = ovm.FirstName, 
        LastName = ovm.LastName, 
        Age = ovm.Age, 
        Gender = ovm.Gender, 
        Disable = ovm.Disable, 
        JoinedDate = DateTime.Now, 
        CarerName = ovm.CarerName, 
        ImagePath = ovm.ImagePath 
       }); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 

      return View(ovm); 
     } 

,所以我面临的问题是在这里说,在ovm.ImageFile {“未将对象引用设置到对象的实例。”}。HELP

string fileName = Path.GetFileNameWithoutExtension(ovm.ImageFile.FileName); 

回答

1

需要在前端定义形式的内容类型 - ENCTYPE = “多部分/格式数据”

<form method="post" enctype="multipart/form-data" action="/ActionPath"> 
+0

我怎么能忘记..谢谢:) – Sres

+0

它已经被添加? –

+0

不,我忘了补充。它在加入后有效 – Sres