我上传和图片,并验证它的有效性在这里:然而,我的例子略有不同,因为我不仅收到文件,我也收到了一些属性为我的模型。但是,我的验证程序总是触发,我调试并发现我的文件总是空的,所以验证器总是返回'false‘。我不明白为什么,我的意见似乎是正确的。有什么想法吗?
namespace PhotoManagement.Models
{
public class Photo
{
public virtual int PhotoId { get; set; }
public virtual int ClientId { get; set; }
public virtual string PhotoDescription { get; set; }
[ImageValidation(ErrorMessage="Please select a PNG/JPEG image smaller than 10 MB")]
[NotMapped]
public HttpPostedFileBase File { get; set; }
}
} [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Photo photo)
{
if (ModelState.IsValid)
{
db.Photos.Add(photo);
db.SaveChanges();
// File upload occurs now
var FilePath = Path.Combine(Server.MapPath("~/App_Data/" + photo.ClientId), photo.PhotoId.ToString());
photo.File.SaveAs(FilePath);
return RedirectToAction("Create");
}
else return View();
}@using (Html.BeginForm(new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Photo for @Session["Name"]</legend>
<div class="editor-field">
@Html.Hidden("ClientId",(int)Session["UserId"])
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PhotoDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhotoDescription)
@Html.ValidationMessageFor(model => model.PhotoDescription)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.File)
</div>
<div class="editor-field">
<input type="file" name="File" id="File"/>
@Html.ValidationMessageFor(model => model.File)
</div>发布于 2013-06-03 13:02:17
您正在使用错误的Html.BeginForm助手重载。
正确的呼吁是:
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}你在打电话:
Html.BeginForm(object routeValues)而不是:
Html.BeginForm(
string actionName,
string controllerName,
FormMethod method,
object htmlAttributes
)看看浏览器中生成的标记,您就会看到根本的区别。
发布于 2013-06-03 12:56:19
而不是
public ActionResult Create(Photo photo)试一试
public ActionResult Create(Photo photo, HttpPostedFileBase file)编辑:不要忘记将HTTP设置为在视图中发布:
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))发布于 2013-06-03 13:03:45
Model中的文件总是会给出null。为了获得文件:
[HttpPost]
public ActionResult Create(UserViewModel model,
FormCollection formCollection, HttpPostedFileBase file){
/* Your code here */
if(file==null)
{
ModelState.AddModelError("NoFile", "Upload File");
}
}在这里,HttpPostedFileBase文件将为您提供上传文件的完整对象。可以对对象文件进行检查。不要忘记在视图中添加下面提到的验证消息。
@Html.ValidationMessage("NoFile")https://stackoverflow.com/questions/16897077
复制相似问题