嗨,我有这个自定义验证,但在要验证的属性类型上略有不同,即使我符合业务规则,ModelState 的值也始终是“null”=s ...这里有一些代码
模型
[System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "image")]
[ValidateFile(Allowed = new string[] { ".png", ".jpeg", ".jpg" },
MaxLength = 1024 * 1024 * 3,
ErrorMessage = "Please select a PNG , JPEG , JPG image smaller than 3MB")]
public byte[] Photo { get; set; }
===========
验证文件属性
public class ValidateFileAttribute : RequiredAttribute
{
public int MaxLength { get; set; }
public string[] Allowed { get; set; }
public override bool IsValid(object **value**)
{
var Photo = value as HttpPostedFileBase;
if (Photo == null)
{
return false;
}
if (Photo.ContentLength > MaxLength)
{
return false;
}
if (!Allowed.Contains(Photo.FileName.Substring(Photo.FileName.LastIndexOf('.'))))
{
return false;
}
return true;
}
这里是值不应该为空的地方!!
创建.cshtml
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Restaurant</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Country)
@Html.ValidationMessageFor(model => model.Country)
</div>
<div class="editor-label">
@Html.LabelFor(model=>model.Photo)
</div>
<div class="editor-field">
@Html.EditorFor(model=>model.Photo)
@Html.ValidationMessageFor(model => model.Photo)
<input name="ImageFile" type="file" id="ImageFile" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
有什么帮助吗?