【发布时间】:2020-12-13 01:40:36
【问题描述】:
大家好,
我正在尝试将图像上传到文件夹并使用 ASP.NET MVC 代码优先方法将路径 URL 保存在数据库中。
在保存 URL 路径时,它返回 Object referenced Null。
下面是表单保存时调用的动作方法。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Account_Number,Title,Firstname,Othername,Surname,Phone_Number,Bank_AccountName, Bank_Fullname, img_Passport")] SavingsAccount savingsAccount, HttpPostedFileBase postedFile)
{
Thread.Sleep(2000);
//Extract Image File Name.
string fileName = "1000000005";
//Set the Image File Path.
string filePath = "~/Images/Uploads/SavingsAccount/" + fileName;
//Save the Image File in Folder.
postedFile.SaveAs(Server.MapPath(filePath));
if (ModelState.IsValid)
{
savingsAccount.Account_Number = Account_No;
savingsAccount.Account_Type = "Savings Account";
savingsAccount.Account_Balance = 0;
savingsAccount.Date_Opened = Convert.ToDateTime(DateTime.Now.ToString());
savingsAccount.Opened_By = User.Identity.Name;
savingsAccount.img_Passport = filePath; //Insert the Passport URL Path to database
db.SavingsAccounts.Add(savingsAccount);
db.SaveChanges();
return View("DisplaySuccessMessage");
}
return View(savingsAccount);
}
当我使用断点检查发送的值时,Posted 文件被视为 Null。
我做错了吗?
【问题讨论】:
-
我认为这是因为在
view页面中没有将new { enctype = "multipart/form-data" })参数添加到@html.BeginForm。使用此“@using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, new { enctype = "multipart/form-data" }))" 创建表单 -
正是问题所在。非常感谢
标签: c# asp.net-mvc