Display error message in jQuery popup or in alert in MVC 4
Asked Answered
S

3

6

Am using DataAnnotation for validation, I want to show the error message(Data annotation) in a pop up (dialog/alert) instead of showing it on view.... I have implemented the code using this link..

Project template is Mobile Let me know if I am missing something ?? http://forums.asp.net/t/1738076.aspx/1

Javascript:-

$('#Test').bind('invalid-form.validate', function (form, validator) {
    alert('InsideTest');   
     var $list = $('#errorlist ul:first')
     if ($list.length && validator.errorList.length) {
            $list.empty();
            $.each(validator.errorList, function () {
                $("<li />").html(this.message).appendTo(list);
            });
            $list.dialog({
                title: 'Please correct following errors:',
            });
 }
});
Forgot to add html...    

About.cshtml :-

@model WRDSMobile.Models.Test

<div id="errorlist" style="display:none"><ul></ul></div>    
@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "Test", id = "Test" }))
{
     @Html.ValidationSummary(true)
     <fieldset>

        <legend>Test</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.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>  
            <input type="submit" value="Create" />
    </fieldset>
}
Sly answered 11/3, 2013 at 12:30 Comment(4)
Forgot to add html...Sly
No issues, you can edit and update the question :)Wristband
What's your question? Are you encountering some problem with this code?Dumb
Am not getting any error.. Form gets directly postedSly
M
1

I'm not sure if I understand your question, but you can ajax post to your controller and return a partial view. Then load the partial view into your html element and then pop it up in a dialog box.

 [HttpPost]
    public ActionResult validate(string firstName,string lastName){

        //logic here for validation
         return PartialView();
    }


$.ajax({
            type: "POST",
            data: {firstName: nameVal, lastName: lastNameVal },
            url: "/myController/validate",
            dataType: "html",
            success: function (data) {
                if (data) {
                    var dialog = $('<div></div>');
                    dialog.html(data);
                    dialog.dialog({
                        resizable: false,
                        modal: true,
                        overflow: false,
                        maxWidth: 1200,
                        maxHeight: 600,
                        width: 1200,
                        height: 600,
                        border: 0,
                        buttons: {
                            "Cancel": function () { //cancel
                                $(this).dialog("close");
                            }
                        }

                    });
                }
                else {
                    alert("error");

                }
            }
        });
Maples answered 12/3, 2013 at 23:18 Comment(1)
Well I need to show data annotation(client side) error in popupSly
R
1

Add below following CSS/JS as referance jquery-ui.css, jquery-1.8.2.min.js, jquery-ui-1.8.24.min.js, jquery.validate.min.js, jquery.validate.unobtrusive.min.js

$(document).ready(function () {
        $('#Test').bind('invalid-form.validate', function (form, validator) {
            var $list = $('<ul />')
            if (validator.errorList.length) {
                $.each(validator.errorList, function (i, entity) {
                    $("<li />").html(entity.message).appendTo($list);
                });
                msgbox('Please correct following errors:', $('<div />').append($list));
                return false;
            }
        });
    });

    function msgbox(_title, _messageHtml) {
        $('<div></div>').appendTo('body')
                    .html(_messageHtml)
                    .dialog({
                        modal: true, title: _title, zIndex: 10000, autoOpen: true,
                        width: 'auto', resizable: false,
                        buttons: {
                            Ok: function () {
                                // $(obj).removeAttr('onclick');                                
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");
                            }
                        },
                        close: function (event, ui) {
                            $(this).remove();
                        }
                    });
    };
Reinert answered 3/1, 2014 at 14:8 Comment(1)
Thanks, Currently am using jquery validate but I was checking if it can help some others, Error message comes in pop up as well on htmlSly
P
0

public static void method(this ModelStateDictionary modelState)

    {
        StringBuilder errors = new StringBuilder();
        try
        {
            foreach (ModelState model_State in modelState.Values)
                foreach (ModelError error in model_State.Errors)
                    errors.AppendLine(error.ErrorMessage.ToString());
            if (errors.Length > 1)
                throw new Exception();
        }
        catch (Exception ex)
        {
            throw new // your validation helper
        }

}

catch this in ajax sucess false open jquery dialog with this error error message Note : use mvc error handler it will send the error message with ajax success= false

Polysaccharide answered 10/12, 2013 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.