嗨我有這個自定義驗證,但有一點差異待驗證的屬性的類型,並且總是即使我如果符合業務規則ModelState的值是「空」 = S ...這裏的一些代碼自定義HttpAttribute覆蓋時驗證IsValid(對象值)始終爲空
型號
[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>
}
任何幫助嗎?
感謝您的回答,我確實嘗試了您發佈的內容並修復了一些邏輯,但即使當我將var Photo = value更改爲[] –
時,值仍然爲null然後,您不會爲Photo屬性分配任何內容。 –