mardi 12 janvier 2016

Data Annotation not working with Ajax Form Upload

I am unable to determine why my Razor View Page is not able to show Model Errors. I have applied Data Annotation to my model class. I am submitting the form using Ajax Form Upload Plugin (See Reference -> http://ift.tt/PEjYy2).

Model Class

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;
                }
            }
}

Controller

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);
    }

View

@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) &nbsp;&nbsp;
                @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>

On Controller ,ModelState.IsValid becomes false if any of the model property doesn't validate but it is not displaying error on view page. Don't know why. can anybody tell me.

Note* : I am not using Ajax.BeginForm here because i can't able to upload files with this approach. So instead i am using jquery form upload puglin.

Any help would be appriciated. If you need to know anything let me know here.

Aucun commentaire:

Enregistrer un commentaire