我在 ASP.NET MVC 中添加影像時遇到了一些問題。我在我的根檔案夾中創建了一個檔案夾,命名為/Images/Brands/我想要保存品牌模型影像的位置。
這是我的Brand模型:
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; }
}
}
我看到有些人將路徑保存在模型類中,ImagePath然后在需要時從ImagesPath.
這是我創建品牌的功能:
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>
uj5u.com熱心網友回復:
您的 Create 方法正在接受序列化模型,雖然模型可以包含檔案資料,但它可能無法決議名稱:
這應該有效:
@Html.TextBoxFor(model => model.ImageFile, new { type="file" })
這將確保結果輸入被命名,以便 MVC 將在表單提交或序列化模型上識別它。
如果這不起作用,接下來要檢查的是設定斷點string filename = Path.GetFileName(brand.ImageFile.FileName);并檢查哪個部分是#null。是ImageFilenull 還是ImageFile.FileName? 您還應該驗證您的代碼以檢查空值,以防可以在不提供檔案的情況下提交表單。
uj5u.com熱心網友回復:
問題出在 Create.cshtml 視圖中:
@using (Html.BeginForm())
解決方案是:
@using (Html.BeginForm("Create","Brands", FormMethod.Post, new { enctype = "multipart/form-data" }))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375782.html
標籤:C# 。网 sql-server asp.net-mvc 实体框架
