为什么我的帖子不以 MVC.NET 发布图像

本文关键字:布图像 图像 NET MVC 我的 为什么 | 更新日期: 2023-09-27 18:30:37

视图中的输入:

@using (Html.BeginForm("Create", "Articles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 <td><input type="file" name="Img" id="Img"/></td>
}

我的图像对象的模型:

  public class Image
  {
    public int ID { get; set; }
    [AllowHtml]
    public string Contents { get; set; }
    public byte[] Img { get; set; }
    public int Articleid { get; set; }
  }

控制器:

    public ActionResult Create()
    {
        return View();
    } 
    //
    // POST: /Articles/Create
    [HttpPost]
    public ActionResult Create(Article article , HttpPostedFileBase img)
    {
      var whatisPosted = Request.Form.AllKeys.ToList();
        if (ModelState.IsValid)
        {
            context.Articles.Add(article);
            context.SaveChanges();
            return RedirectToAction("Index");  
        }
        return View(article);
    }

所以发布的内容没有图像.....不知道为什么...但是我发布的其他内容已正确发布....那么为什么它不起作用呢?-_-

为什么我的帖子不以 MVC.NET 发布图像

您可以从HttpContext.Request.Files["Img"]获取发布的图像

HttpPostedFileBase img = HttpContext.Request.Files["Img"];

编辑:

您也可以重命名 Crate 操作的 HttpPostedFileBase 参数,以匹配 html 中的"name"属性。

public ActionResult Create(Article article , HttpPostedFileBase Img) <-- capital "I"

首先,你的视图不包含一个提交按钮 - 你需要一个(例如,除非你使用jQuery库中的.submit())。这会向服务器发送 HTTP POST 请求 - 然后您的控制器能够处理它。

article对象将始终为 null,因为它永远不会启动。请尝试以下代码:

视图:

@model ArticleFormViewModel
@using (Html.BeginForm("Create", "Articles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <td>
    @Html.LabelFor(m => m.ImageFile)
    @Html.TextBoxFor(m => m.ImageFile, new { type = "file" })
  </td>
  <input type="submit" value="Upload" class="submit" />
}

型号:

public class ArticleFormViewModel
{
  [AllowHtml]
  public string Contents { get; set; }
  [DataType(DataType.Upload)]
  public HttpPostedFileBase ImageFile { get; set; }
}
public class Image
{
  public int ImageID { get; set; }
  ...
}
public class Article
{
  public int ArticleID { get; set; }
  ...
}

控制器:

[HttpGet]
public ActionResult Create()
{
  ArticleFormViewModel Model = new ArticleFormViewModel();
  return View(Model);
}
[HttpPost]
public ActionResult Create(ArticleFormViewModel Model)
{
 if(ModelState.IsValid)
 {
   if(Model.ImageFile != null)
   {
     var path = Path.Combine(Server.MapPath("~/articles"), Model.ImageFile.FileName);
     try
     {
       Model.ImageUpload.SaveAs(imagePath);
       //Perhaps then save Entity to database using an ORM?
     }
     catch(Exception e)
     {
       //Do something..
     }
   }
 }
 return View(Model);
}