我无法确定为什么我的Razor View页面无法显示模型错误。我已将Data Annotation应用于我的模型类。我使用Ajax表单上传插件提交表单(参见参考 - > http://malsup.com/jquery/form/)。
模型类
public class Category
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[FileExtensions(Extensions = ".jpeg,.jpg,.png",ErrorMessage ="Please upload valid image format.")]
public string BannerImage { get; set; }
[FileExtensions(Extensions = ".jpeg,.jpg,.png", ErrorMessage = "Please upload valid image format.")]
public string ThumbImage { get; set; }
private HttpPostedFileBase _bannerImageFile;
[Display(Name = "Banner Image")]
public HttpPostedFileBase BannerImageFile
{
get
{
return _bannerImageFile;
}
set
{
_bannerImageFile = value;
if(value != null)
BannerImage = _bannerImageFile.FileName;
}
}
private HttpPostedFileBase _thumbImageFile;
[Display(Name = "Thumb Image")]
public HttpPostedFileBase ThumbImageFile
{
get
{
return _thumbImageFile;
}
set
{
_thumbImageFile = value;
if (value != null)
ThumbImage = _thumbImageFile.FileName;
}
}
[Display(Name = "Meta Keywwords")]
public string MetaKeywords { get; set; }
[Display(Name = "Meta Description")]
public string MetaDescription { get; set; }
[Display(Name = "Created Date")]
public string CreatedDate { get; set; }
[Display(Name = "Last Updated Date")]
public string LastUpdatedDate { get; set; }
public bool Status { get; set; }
public List<SubCategory> SubCategories { get; set; }
public bool IsSaved(string spNameOrSql, Dictionary<string, object> parameters, QueryType type = QueryType.SQL)
{
try
{
if (type == QueryType.StoredProcedure)
{
var p = new SqlParameter[parameters.Count];
var count = 0;
foreach (var item in parameters)
{
var key = item.Key;
var value = item.Value;
value = String.Join(" ", Convert.ToString(value).Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries));
p[count++] = new SqlParameter("@" + key, value);
}
return Convert.ToBoolean(DataFunctions.ExecuteScalar(spNameOrSql, p, type));
}
return Convert.ToBoolean(DataFunctions.ExecuteScalar(spNameOrSql, type));
}
catch (Exception ex)
{
Error.Log(GetType().Name, MethodBase.GetCurrentMethod().ToString(), ex.Message, ex.Source, ex.StackTrace);
return false;
}
}
}
控制器
public ActionResult AddCategory(Category model)
{
if (ModelState.IsValid)
{
var param = model.GetType().GetProperties().ToDictionary(prop => prop.Name,
prop => prop.GetValue(model, null));
param.Remove(Nameof<Category>.Property(e => e.Id));
param.Remove(Nameof<Category>.Property(e => e.BannerImageFile));
param.Remove(Nameof<Category>.Property(e => e.ThumbImageFile));
param.Remove(Nameof<Category>.Property(e => e.CreatedDate));
param.Remove(Nameof<Category>.Property(e => e.LastUpdatedDate));
var result = model.IsSaved(AppConstants.StoredProcedures.CATEGORY_ADD, param, QueryType.StoredProcedure);
if (result)
{
for (int i = 0; i < Request.Files.Count; i++)
{
switch (Request.Files.Keys[i])
{
case "BannerImageFile":
UploadImage(Request.Files[i], AppConstants.FilePath.CATEGORY_BANNER_IMAGE_PATH);
break;
case "ThumbImageFile":
UploadImage(Request.Files[i], AppConstants.FilePath.CATEGORY_THUMB_IMAGE_PATH);
break;
}
}
ModelState.Clear();
}
}
return PartialView("_PartialAddCategory",model);
}
查看
@model TristarJewelry.Shared.Models.Category
<script type="text/javascript">
$(document).ready(function () {
var options = {
beforeSubmit: BeginLoader,
success: OnSuccess,
error: OnFailure,
target: '#myForm'
};
$('#myForm').ajaxForm(options);
});
function OnSuccess() {
$("#app_message").removeClass("alert-success alert-danger alert-warning alert-info");
$("#app_message").addClass("alert-success");
$("#app_message").html("Category Succesfully Added !");
$("#app_message").fadeIn(2000).delay(2000).fadeOut(2000);
StopLoader();
}
function OnFailure() {
$("#app_message").html("Oops something went wrong ! Try after sometime. ");
$("#app_message").removeClass("alert-success alert-danger alert-warning alert-info");
$("#app_message").addClass("alert-danger");
$("#app_message").fadeIn(2000).delay(3000).fadeOut(2000);
}
function BeginLoader() {
$('#loader').modal({ toggle: "model", backdrop: 'static', keyboard: false });
}
function StopLoader() {
$('#loader').modal("hide");
}
</script>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Category</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Please fill all the details.
</div>
<div class="panel-body">
<div class="row">
<form id="myForm" action="@Url.Action("AddCategory","Dashboard")" method="POST" enctype = "multipart/form-data">
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="col-lg-6">
<div class="form-group">
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Name" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description)
@Html.TextAreaFor(model => model.Description, new { @class = "form-control", @placeholder = "Enter Description", @rows = "3", style = "resize:vertical" })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.ThumbImageFile)
@Html.TextBoxFor(model => model.ThumbImageFile, new { type = "file" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.BannerImageFile)
@Html.TextBoxFor(model => model.BannerImageFile, new { type = "file" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Status)
@Html.CheckBoxFor(model => model.Status)
@Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
</div>
<button type="submit" class="btn btn-default">Submit Button</button>
<button id="form_reset" type="reset" class="btn btn-default">Reset Button</button>
</div>
<!-- /.col-lg-6 (nested) -->
<div class="col-lg-6">
<div class="form-group">
@Html.LabelFor(model => model.MetaKeywords)
@Html.EditorFor(model => model.MetaKeywords, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Meta Keywords" } })
@Html.ValidationMessageFor(model => model.MetaKeywords, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.MetaDescription)
@Html.TextAreaFor(model => model.MetaDescription, new { @class = "form-control", @placeholder = "Enter Meta Description", @rows = "3", style = "resize:vertical" })
@Html.ValidationMessageFor(model => model.MetaDescription, "", new { @class = "text-danger" })
</div>
</div>
<!-- /.col-lg-6 (nested) -->
</form>
</div>
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
在Controller上,如果任何模型属性没有验证但是它没有在视图页面上显示错误,则ModelState.IsValid变为false。不知道为什么。任何人都可以告诉我。
注意*:我这里没有使用Ajax.BeginForm,因为我无法使用这种方法上传文件。所以我使用jquery表单上传puglin。
任何帮助都会得到满足。如果你需要知道任何事情请告诉我。