我对 ASP.NET MVC 非常陌生。我有一个包含一些图像字段的模型 (byte[]
)。
我也创建了 Controller 和 View ,但是当我运行代码时没有任何内容 上传图像字段。我的图像是模型的一些字段,其他字段是字符串。
请帮助我。 Controller 和 View 应该如何?
模型类:
public int Id { get; set; }
public string Name { get; set; }
public string Activity { get; set; }
public string Address { get; set; }
public string Tel { get; set; }
public string Work_Hours { get; set; }
public byte[] img1 { get; set; }
public byte[] img2 { get; set; }
Controller (创建):
public ActionResult Create(Shop shop)
{
try
{
var bytes = new byte[0];
ViewBag.Mime = "image/png";
if (Request.Files.Count == 1)
{
bytes = new byte[Request.Files[0].ContentLength];
Request.Files[0].InputStream.Read(bytes, 0, bytes.Length);
ViewBag.Mime = Request.Files[0].ContentType;
}
db.Shop.Add(shop);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
我的观点的所有部分都是这样的:
<div class="editor-label">
<%: Html.LabelFor(model => model.Activity) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Activity) %>
<%: Html.ValidationMessageFor(model => model.Activity) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.img2) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.img2)%>
<%: Html.ValidationMessageFor(model => model.Shop_img2) %>
</div>
但是我应该用什么来上传图片呢?!
最佳答案
@{ Html.BeginForm("Load", "Image", FormMethod.Post,
new { enctype = "multipart/form-data" }); }
<input id="file" type="file" name="file" />
<input id="submit" type="submit" value="Upload Image" style="display: none;" />
@{ Html.EndForm(); }
[HttpPost]
public ActionResult Load(HttpPostedFileBase file)
{
if (file.ContentLength == 0)
RedirectToAction("LoadImage");
var fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, file.ContentLength);
// save fileByptes here...
return RedirectToAction("Edit");
}
关于asp.net - 如何使用 SQL Server 和 ASP.NET MVC 将图像作为字段插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12825791/