您好,我有这个自定义验证,但在要验证的属性类型上有一些差异,即使我满足业务规则,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; }===========
ValidateFileAtribute
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;
}这里是值不应该为空的地方!!
Create.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>
}有什么帮助吗?
发布于 2013-06-21 13:56:09
您的财产:
public byte[] Photo { get; set; }在属性中:
var Photo = value as HttpPostedFileBase;这将始终为空。尝试:
var Photo = value as byte[]当然,您必须修复验证逻辑的附加部分。
发布于 2013-07-01 23:24:23
我会检查您在byte[]照片中放置的内容,因为我注意到,当输入的数据无效时,“对象值”为空。
一个例子是,对于int的数据类型,当我输入2147483647时,'object value‘包含2147483647。
当我输入2147483648时,value参数包含0,因为最大正整数值为2147483647。
2013年7月5日更新
您需要将数据类型更改为"HttpPostedFileBase“
公共HttpPostedFileBase照片{ get;set;}
代替"byte[]“
公共byte[]照片{ get;set;}
应该不需要
System.ComponentModel.DataAnnotations.Schema.Column(TypeName =“”)
你的
(object **值**)
现在应该包含包含要上载的文件的System.Web.HttpPostedFileWrapper。
这与我之前写的内容是一致的,即如果传入的数据类型不是正确的类型,您将得到一个空。
https://stackoverflow.com/questions/17226513
复制相似问题