【发布时间】:2017-07-10 09:53:00
【问题描述】:
在我的 MVC 4 项目中,我使用“创建强类型视图”作为“脚手架模板:编辑”创建了一个视图。但是在该页面中,我尝试使用文件上传方法上传图像,但在控制器端 HttpPostedFileBase 在我运行项目时始终显示为空。
这是我的控制器:
public ActionResult EditUser(int id)
{
if (Session["UserId"] != null)
{
return View(db.Users.FirstOrDefault(x => x.id == id));
}
else
{
return RedirectToAction("Login");
}
}
[HttpPost]
public ActionResult EditUser(User user, HttpPostedFileBase ProfileImage)
{
db.Entry(user).State = System.Data.EntityState.Modified;
if (ProfileImage != null && ProfileImage.ContentLength > 0)
{
string filePath = Path.Combine(Server.MapPath("~/Content/img/user"), Path.GetFileName(ProfileImage.FileName));
ProfileImage.SaveAs(filePath);
}
db.SaveChanges();
return RedirectToAction("Profile");
}
这是我的观点:
@model emirhanozkan.Models.User
@{
ViewBag.Title = "Edit User";
}
<h2>EditUser</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>@ViewBag.Title</legend>
@Html.HiddenFor(model => model.id)
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProfileImage)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.ProfileImage, new { type = "file", enctype = "multipart/form-data" })
@Html.ValidationMessageFor(model => model.ProfileImage)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
在输入文件系统中获取名称为 ProfileImage。
这是我的模型:
namespace emirhanozkan.Models
{
public partial class User
{
[Key]
public int id { get; set; }
[Required(ErrorMessage = "Lütfen bir kullanıcı adı belirleyiniz.")]
public string Username { get; set; }
[Required(ErrorMessage = "Lütfen email adresinizi giriniz.")]
[RegularExpression(@"^([\w-\.]+)@((\[[0-9]{1,3]\.)|(([\w-]+\.)+))([a-zA-Z{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Lütfen geçerli bir email adresi giriniz.")]
public string Email { get; set; }
public string ProfileImage { get; set; }
}
}
@Html.TextBoxFor(model => model.ProfileImage, new { type = "file", enctype = "multipart/form-data" }) 是我的混合物,我不知道有没有类似的方法,但我尝试使用 @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })){<input type="file" />} 代替我的代码,但效果不佳。
您知道如何在 MVC 4 的“创建强类型视图”中使用 HttpPostedFileBase 吗?
【问题讨论】:
-
除了在
<form>中设置enctype之外,您的属性应该是HttpPostedFileBase而不是string,它将绑定到您的模型(不需要POST 方法中的第二个参数)
标签: c# asp.net-mvc asp.net-mvc-4 razor