简体   繁体   中英

MVC Client Side Validation

Learning MVC 3 and I am trying to use clientside validation in MVC using AJAX:

I have included the suggestions in article Call MVC 3 Client Side Validation Manually for ajax posts , but this does not work for me, it still sees the form as valid. What am I missing??

I have included the following in my aplication:

Root web.config file:

<appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

Layout page scripts:

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

My model:

[Table("Person")]     
public class Person
    {
        [Key]
        public int PersonID { get; set; }
        [Column("FullName")]
        [Required(ErrorMessage = "Give me a name.")]
        public string NameFull { get; set; }
        [Required(ErrorMessage = "Give me an email.")]
        public string EmailAddress { get; set; }
        [Required(ErrorMessage = "Give me a mobile number.")]
        public string MobileNo { get; set; }
        [ForeignKey("Agency")]
        [Required(ErrorMessage = "Give me an agency.")]
        public int AgencyID { get; set; }
        public virtual Agency Agency { get; set; }
    }

The method to do the ajax call (fires on an onclick event):

function LoadPage(SFORM, SACTION, SMETHOD) {
    $('#divLoading').slideDown(1);
    var doc = document.getElementById(SFORM)
    var dataform = $(doc).serialize();
    var $form = $(doc);
    if ($form.valid()) { 
        //Ajax call here 
        $.ajax({
            type: SMETHOD,
            url: SACTION,
            data: dataform,
            complete: function () {
                $("#divLoading").slideUp(1, function () { FinishLoad() });

            },
            success: function (data) {
                $("#divMain").html(data)

            }
        });
    }
}

The View (.cshtml):

<form id="frmCreate" name="frmCreate">
    @Html.ValidationSummary(true)
            <fieldset>
                <legend>Person</legend>

                <div class="editor-label">
                    @Html.LabelFor(model => model.NameFull)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.NameFull)
                    @Html.ValidationMessageFor(model => model.NameFull)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.EmailAddress)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.EmailAddress)
                    @Html.ValidationMessageFor(model => model.EmailAddress)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.MobileNo)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.MobileNo)
                    @Html.ValidationMessageFor(model => model.MobileNo)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.AgencyID, "Agency")
                </div>
                <div class="editor-field">
                    @Html.DropDownList("AgencyID", String.Empty)
                    @Html.ValidationMessageFor(model => model.AgencyID)

                </div>

                <p>
                   <input type="button" value="Create" onclick="LoadMenuItem('frmCreate','@Url.Action("Create", "Person")', 'POST')" />
                </p>
            </fieldset>
</form>

Seemed to have figured it out, it seems you have to use the @using (Html.BeginForm(null, null, FormMethod.Get, new { name = "validator", id = "validator" })) to create the form and not the standard tag and then assign the form you want to validate using the a script at the bottom of the view you would like to validate $.validator.unobtrusive.parse("#validator");

The great thing about this is that on your layout page you may have a "parent form" with a different ID wich may wrapcontain hidden fields that you might want to post with the validated form and all you have to do is post the parent form but the validation will still occur on the form that you assign within the script $.validator.unobtrusive.parse("#validator"); on your partial views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM