在视图中输入:
@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);
}
所以发布的内容没有形象......不知道为什么......但我发布的其他内容是正确发布的......那么为什么它不起作用? -_-
答案 0 :(得分:1)
您可以从HttpContext.Request.Files["Img"]
HttpPostedFileBase img = HttpContext.Request.Files["Img"];
编辑:
您也可以重命名Crate操作的HttpPostedFileBase参数以匹配&#34; name&#34;你的HTML中的属性。
public ActionResult Create(Article article , HttpPostedFileBase Img) <-- capital "I"
答案 1 :(得分:1)
首先,您的View不包含提交按钮 - 您需要一个(例如,除非您使用jQuery库中的.submit()
)。这会向服务器发送HTTP POST请求 - 然后您的Controller可以处理它。
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);
}