0

在我的模型所在的类文件中,我具有必需的属性,例如:

[Required]
        [Range(0, 99, ErrorMessage = "Sorry, you must select a range between 0 - 99.")]
        public int MaxConcurrentUsers { get; set; }

因此,您会认为,当我单击页面上的提交按钮以发布值时,因为我为 MaxConcurrentUsers 键入了不正确的值,所以它不会到达我的 C# 代码中的 actionResult 方法。但确实如此。我注意到的一件事是我的模型状态 .valid 是错误的,但我希望客户端阻止它使用该方法。我究竟做错了什么?

我的模型

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace UserManager.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class vw_UserManager_Model
    {
        public string rowtype { get; set; }
        public System.Guid applicationid { get; set; }
        public System.Guid userid { get; set; }

    //    [StringLength(12, MinimumLength = 6,
    //ErrorMessage = "Username must be between 6 and 12 characters.")]
        public string UserName { get; set; }

        [Required]
        [Range(0, 99, ErrorMessage = "Sorry, you must select a range between 0 - 99.")]
        public int MaxConcurrentUsers { get; set; }

        [Required(ErrorMessage = "First name is a required field")]
        [Display(Name = "First name")]
        public string firstname { get; set; }

        [Required(ErrorMessage = "Last name is a required field")]
        [Display(Name = "Last name")]
        public string lastname { get; set; }

        public string salutation { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string password { get; set; }

        [Required(ErrorMessage = "Email is required.")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string email { get; set; }

        public string group_name { get; set; }
        public Nullable<long> group_id { get; set; }
        public int moduleid { get; set; }
        public Nullable<int> session_status { get; set; }
        public Nullable<int> islockedout { get; set; }
        public Nullable<bool> isactive { get; set; }

        public bool IsApproved { get; set; }

        public bool alf { get; set; }
        public bool brad { get; set; }

        public string module_name { get; set; }

        public string CompanyName { get; set; }
        public string CompanySearch { get; set; }

        public string selected_module { get; set; }
        public string selected_group { get; set; }

        public string selected_moduleAlf { get; set; }
        public string selected_moduleBrad { get; set; }

        public string selected_groupAlf { get; set; }
        public string selected_groupBrad { get; set; }
    }
}

我的观点

@model UserManager.Models.vw_UserManager_Model 
<h2 style="padding-left: 25px;">
    Create user</h2>
@using (Html.BeginForm())
{
    <!-- ALF/BRAD selection -->
    @Html.ValidationSummary(true)
    <fieldset style="width: 400px; padding-left: 15px;">
        <legend>Select module type:</legend>
        <div class="module-selection">
            @Html.Label("Select ALF")
            <input type="checkbox" checked="checked" id="chkAlf" name="selection" value="Alf"
                onclick="chkSelection()" />
            @Html.Label("Select BRAD")
            <input type="checkbox" id="chkBrad" name="selection" value="Brad" onclick="chkSelection()" />
        </div>
    </fieldset>

    <!-- Module selection -->
    <fieldset style="width: 400px; padding-left: 15px;">
        <legend>Select module:</legend>
        <div id="alfModules">
            @{Html.RenderAction("_CreateUserModulesAlf", "UserManager");}
        </div>
        <br />
        <div id="bradModules">
            @{Html.RenderAction("_CreateUserModulesBrad", "UserManager");}
        </div>
    </fieldset>

    <!-- Check if group exists -->
    <fieldset style="width: 400px; padding-left: 15px;">
        <legend>Group Checker</legend>
        <div id="createuser-groupnamesearch">
            @{Html.RenderAction("_txtGroupSearchForm", "UserManager");}
        </div>
    </fieldset>

    <fieldset style="width: 400px; padding-left: 15px;">
        <legend>New User Details</legend>
        <div class="editor-label">
            @Html.LabelFor(Model => Model.salutation)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(Model => Model.salutation, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Mr", Value = "Mr" }, 
                        new SelectListItem{ Text="Mrs", Value = "Mrs" },
                        new SelectListItem{ Text="Miss", Value = "Miss" },
                        new SelectListItem{ Text="Ms", Value = "Ms" },
                        new SelectListItem{ Text="Dr", Value = "Dr" }
                     })
            @Html.ValidationMessageFor(model => Model.salutation)
        </div>
        <div id="createuser-usernamesearch">
            @{Html.RenderAction("_txtUsernameSearch", "UserManager");}
        </div>
        <div class="editor-label">
            @Html.Label("Firstname")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.firstname)
            @Html.ValidationMessageFor(model => Model.firstname)
        </div>
        <div class="editor-label">
            @Html.Label("Surname")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.lastname)
            @Html.ValidationMessageFor(model => Model.lastname)
        </div>
        <div class="editor-label">
            @Html.Label("Password")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.password)
            @Html.ValidationMessageFor(model => Model.password)
        </div>
        <div class="editor-label">
            @Html.Label("Email")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.email)
            @Html.ValidationMessageFor(model => Model.email)
        </div>
        <div class="editor-label">
            @Html.Label("Is active")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.isactive)
            @Html.ValidationMessageFor(model => Model.isactive)
        </div>
        <div class="editor-label">
            @Html.Label("Maximum concurrent users")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => Model.MaxConcurrentUsers)
            @Html.ValidationMessageFor(model => Model.MaxConcurrentUsers, "Enter a number between 0-99.")
        </div>
        <div id="moduleSelection">
            @Html.HiddenFor(Model => Model.selected_moduleAlf, new { id = "hdnModuleAlf" })
            @Html.HiddenFor(Model => Model.selected_moduleBrad, new { id = "hdnModuleBrad" })
        </div>
        <input type="submit" value="Create" onclick="return submitWith();" />
        <span id="validationMessage"></span>
        <br />
        <br />
        @Html.ActionLink("Back to List", "Index")
    </fieldset>


    <div>
        @Html.ValidationSummary()
    </div>

}
<script type="text/javascript">

    // Count checkboxes that are checked.
    function submitWith() {
        var checkedCount = $("input:checked").length;
        var valid = checkedCount > 0;

        // Check that one checkbox is checked first
        if (!valid) { // IF false
            $('#validationMessage').html('You must select at least one option').css("background-color", "red");
        }


        // Second check ALF
        else if ($('.module-selection #chkAlf').is(':checked')) {
            if ($("#txtGroupnameExistsAlf").val() == "Alf Group doesn't exist.") {
                valid = false;
                $('#validationMessage').html('Group must exist in ALF Database first').css("background-color", "red");
            }
            if ($("#txtGroupnameExistsAlf").val() == "") {
                valid = false;
                $('#validationMessage').html('A group must be picked when creating a new user.').css("background-color", "red");
            }
        }


        // Third check
        else if ($('.module-selection #chkBrad').is(':checked')) {
            if ($("#txtGroupnameExistsBrad").val() == "Brad Group doesn't exist.") {
                valid = false;
                $('#validationMessage').html('Group must exist in BRAD Database first').css("background-color", "red");
            }
            if ($("#txtGroupnameExistsBrad").val() == "") {
                valid = false;
                $('#validationMessage').html('A group must be picked when creating a new user.').css("background-color", "red");
            }
        }


        else {
            valid = true;
        }

        return valid;
    }

    function chkSelection() {
//        alert("check selection");
        filters = new Object();

        if ($('.module-selection #chkAlf').is(':checked')) {
            // Show Div
            $("#alfModules").show();
            $("#groupname-checker-alf").show();

            // Show username checker for Alf
            $("#username-checker-alf").show();
            // Set ALF model property to true
            $("#hdnAlf").val("true");
            // Set alf value for one to be passed to Ajax request
            filters.alf = 1;

            var selectedVal = $("#ddlSelectedAlf :selected").val();
            $('#hdnModuleAlf').val(selectedVal);

        }
        else {
            $("#alfModules").hide();
            $("#groupname-checker-alf").hide();
            $("#hdnAlf").val("false");
            $("#username-checker-alf").hide();
            filters.alf = 0;

            $('#hdnModuleAlf').val("false");
            $("#txtGroupnameExistsAlf").val("").css("background-color", "white");
        }

        if ($('.module-selection #chkBrad').is(':checked')) {
            // Show Div
            $("#bradModules").show();
            $("#groupname-checker-brad").show();
            // Show username checker for Alf
            $("#username-checker-brad").show();
            // Set alf value for one to be passed to Ajax request
            filters.brad = 1;

            var selectedVal = $("#ddlSelectedBrad :selected").val();
            $('#hdnModuleBrad').val(selectedVal);


        }
        else {
            $("#bradModules").hide();
            $("#groupname-checker-brad").hide();
            $("#hdnBrad").val("false");
            $("#username-checker-brad").hide();
            filters.brad = 0;

            $('#hdnModuleBrad').val("false");
            $("#txtGroupnameExistsBrad").val("").css("background-color", "white");
        }
        filters.username = $('#createuser-usernamesearch #user_name').val();
        return filters;
    }


    function searchUsername() {
        var filters = chkSelection();
        $.ajax({
            url: '@Url.Action("UsernameSearch", "UserManager")',
            type: "POST",
            async: true,
            dataType: "json",
            data: "username=" + filters.username,
            success: function (data) {
                var usernameExistsAlf = parseInt(data.usernameAlf);
                if (usernameExistsAlf > 0) {
                    $('#txtUsernameExistsAlf').val("Username already exists").css("background-color", "red");
                }
                else {
                    $('#txtUsernameExistsAlf').val("Username doesn't exist").css("background-color", "#33ff00");
                }

                var usernameExistsBrad = parseInt(data.usernameBrad);
                if (usernameExistsBrad > 0) {
                    $('#txtUsernameExistsBrad').val("Username already exists").css("background-color", "red");
                }
                else {
                    $('#txtUsernameExistsBrad').val("Username doesn't exist").css("background-color", "#33ff00");
                }
            },
            error: function (data) {

            }
        });
    }

    $("#group_name").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("LookUpGroupName", "UserManager")',
                dataType: "json",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    value: request.term
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        //                            alert(item.group);
                        return {
                            label: item.group,
                            value: item.group
                        } // end of return

                    })); // end of response

                }, // end of success
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);
                } // end of error
            }); // end of ajax
        },
        minLength: 2,
        select: function (event, ui) { // Assign to hidden values to trigger onchange ajax call.

            $.ajax({
                url: '@Url.Action("GroupnameCheck", "UserManager")',
                dataType: "json",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    value: ui.item.label
                },
                success: function (data) {
                    $.each(data, function (index, value) {
                        if (index == "AlfGroup") {
                            $("#txtGroupnameExistsAlf").val(value);
                            if ($("#txtGroupnameExistsAlf").val() == "Alf Group doesn't exist.") {
                                $("#txtGroupnameExistsAlf").css("background-color", "red");
                            }
                            else {
                                $('#txtGroupnameExistsAlf').css("background-color", "#33ff00");
                            }
                        }

                        if (index == "BradGroup") {
                            $("#txtGroupnameExistsBrad").val(value);
                            if ($("#txtGroupnameExistsBrad").val() == "Brad Group doesn't exist.") {
                                $("#txtGroupnameExistsBrad").css("background-color", "red");
                            }
                            else {
                                $('#txtGroupnameExistsBrad').css("background-color", "#33ff00");
                            }
                        }
                    });
                }, // end of success
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);
                } // end of error
            }); // end of ajax

            $('#hdnGroupAlf').val(ui.item.label);
            $('#hdnGroupBrad').val(ui.item.label);
        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });

    $(document).ready(function () {
        chkSelection();
    });
</script>

我的所有脚本布局

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <!-- Javascript -->
    <script src="../../Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
    @* <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.autocomplete.js")" type="text/javascript"></script>
         <script src="@Url.Content("~/Scripts/Custom/autocompleteGroup.js")" type="text/javascript"></script>*@
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <!-- Javascript -->
    <!-- Stylesheets -->
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.autocomplete.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.autocomplete.custom.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <!-- Stylesheets -->
</head>
<body>
    <div class="page">
        <div id="header">
           <div id="title" >
    <h1>ALF and BRAD User Manager</h1>
</div>
<div id="logindisplay">
    <span style="color:Black; background-color:white;  text-align:right;">
        Logged in as:&nbsp<strong>@Context.User.Identity.Name</strong>
    </span> 
</div>

            <nav>
                <ul id="menu">
                    @Html.ActionLink("User Manager Dashboard", "Index", "UserManager")&nbsp&nbsp
                    @Html.ActionLink("User Analytics", "Index", "UserStatus")&nbsp&nbsp
                    @Html.ActionLink("Email Distibution", "Index", "EmailDistributionList")&nbsp&nbsp
                    @Html.ActionLink("Email User Details", "Index", "EmailUserDetails")&nbsp&nbsp
                </ul>
            </nav>
        </div>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>
@*  <script type="text/javascript">
            $(document).ready(function () {
                doAutocomplete('@Url.Action("LookUpGroupName", "UserManager")');
            });
</script>*@ 

那么有什么帮助吗?谢谢!

4

2 回答 2

3

这就是它应该如何工作的方式。您仍然会使用该方法,但可以检查 ModelState 以决定要做什么,例如...

if (ModelState.IsValid) {
    // Save, redirect to action
}

return View(model); // send them back to correct the problem!

您还可以在视图上显示错误,因为它们将存在。您可以使用 aValidationSummary或拥有单独的ValidationFor元素。

于 2013-01-04T11:05:39.630 回答
0

Check the below link. It may help you.

Client side validation

Update:

You need to enable clientside validation, unobtrusivejavascript and refer the script files in master page.

[web.config]

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

[layout.cshtml]

 <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>
于 2013-01-04T11:11:05.667 回答