[英]ASP.NET MVC upload images to a model
我在 ASP.NET MVC 中添加圖像時遇到了一點問題。 我在我的根文件夾中創建了一個名為/Images/Brands/
的文件夾,我想在其中保存我的品牌模型的圖像。
這是我的Brand
model:
namespace AspProjectBootstrap.Models
{
public class Brand
{
public int ID { get; set; }
[Required]
public String Name { get; set; }
[Required]
public String Description { get; set; }
public virtual ICollection<Product> Products { get; set; }
public String ImagePath { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
}
}
我看到有些人將模型 class 中的路徑保存為ImagePath
,然后在需要時從ImagesPath
獲取圖像的完整路徑。
這是我創建的品牌 function:
public ActionResult Create(Brand brand)
{
string filename = Path.GetFileName(brand.ImageFile.FileName);
filename = DateTime.Now.ToString("yymmssfff") + filename+".png";
brand.ImagePath = "~/Images/Brands/" + filename;
filename = Path.Combine(Server.MapPath("~/Images"), filename);
brand.ImageFile.SaveAs(filename);
if (ModelState.IsValid)
{
db.Brands.Add(brand);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(brand);
}
但我得到一個錯誤。
如果您有任何想法如何解決此問題,或任何其他方法來完成此任務。
先感謝您。
錯誤是:
創建Create.cshtml
視圖是:
<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" />
</div>
</div>
您的 Create 方法正在接受序列化的 model,雖然 model 可以包含文件數據,但它可能無法解析名稱:
這應該有效:
@Html.TextBoxFor(model => model.ImageFile, new { type="file" })
這將確保生成的輸入被命名,以便 MVC 在表單提交或序列化 model 時識別它。
如果這不起作用,接下來要檢查的是在string filename = Path.GetFileName(brand.ImageFile.FileName);
上放置一個斷點。 並檢查哪個部分是#null。 是ImageFile
null 還是ImageFile.FileName
? 您還應該驗證您的代碼以檢查空值,以防可以在不提供文件的情況下提交表單。
問題出在 Create.cshtml 視圖中:
@using (Html.BeginForm())
解決方案是:
@using (Html.BeginForm("Create","Brands", FormMethod.Post, new { enctype = "multipart/form-data" }))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.