提问者:小点点

使用ViewModel进行远程验证。 在viewmodel中列出属性


我正在尝试对我的booking web应用程序中的一些属性进行远程验证。

public class ReservationVM
{
    public Rsvn ReservationInfo { get; set; } // Model for Reservation
    public AdminFilterRsvn FilterAdmin { get; set; } // Model for Filter in Admin Panel ???
    public IEnumerable<Rsvn> ReservationQuery { get; set; } // Query of All Reservations in Database
    public IEnumerable<AvailableRooms> AvailableRooms { get; set; } // Query of All Free and Reserved Rooms SearchResult View
    public List<Room> RoomList { get; set; } // List of Rooms
    public List<Guest> GuestList { get; set; } // List of Guests

}

该VM的视图为:

@model Reservations.ViewModels.Reservation.ReservationVM

@{
    ViewBag.Title = "Reservation";
    Layout = "~/Views/Shared/_MakeReservationLayoutPage.cshtml";
}

<script src="~/Scripts/jquery-ui-1.12.1.js"></script>

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post, new { @id = "rsvnForm" }))
{

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class="text-danger"})
    <div id="rsvnInfo" class="container border border-danger">
        <br />
        <h5 class="text-center">Обща информация за резервацията</h5>
        <div class="form-group">
            <span class="form_label">Смяна</span>

            @Html.HiddenFor(m => m.ReservationInfo.Period)
            @Html.DropDownListFor(m => m.ReservationInfo.Period, Model.ReservationInfo.PeriodList, "Изберете смяна", new { @class = "form-control", @id = "dropDownList", @readonly = true, @disabled = "disabled" })
            @Html.ValidationMessageFor(m => m.ReservationInfo.Period, "", new { @class = "text-danger" })
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <span class="from-label">Дата от</span>
                    <div class="form-group">

                        @*@Html.TextBoxFor(model => Model.ReservationInfo.BegDATE, "{0:dd-MM-yyyy}", new { @id = "BegDATE", @class = "form-control", @placeholder = "Начална дата", @readonly = true })*@
                        @*@Html.EditorFor(model => Model.ReservationInfo.BegDATE, new { htmlAttributes = new { @id = "BegDATE", @class = "form-control", @placeholder = "Начална дата", @readonly = true } })*@
                        @Html.EditorFor(model => Model.ReservationInfo.BegDATEDescription, new { htmlAttributes = new { @id = "BegDATE", @class = "form-control", @placeholder = "Начална дата", @readonly = true } })
                        @Html.HiddenFor(model=>Model.ReservationInfo.BegDATE)
                    </div>
                    @Html.ValidationMessageFor(model => model.ReservationInfo.BegDATEDescription, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="col-sm-6">
                <div class="form-group">
                    <div class="form-group">
                        <span class="from-label">Дата до</span>
                        <div class="form-group">


                            @*@Html.TextBoxFor(model => Model.ReservationInfo.EndDATE, "{0:dd-MM-yyyy}", new { @id = "EndDATE", @class = "form-control", @placeholder = "Начална дата", @readonly = true })*@
                            @*@Html.EditorFor(model => Model.ReservationInfo.EndDATE, new { htmlAttributes = new { @id = "EndDATE", @class = "form-control", @placeholder = "Крайна дата", @readonly = true } })*@
                            @Html.EditorFor(model => Model.ReservationInfo.EndDATEDescription, new { htmlAttributes = new { @id = "EndDATE", @class = "form-control", @placeholder = "Крайна дата", @readonly = true } })
                            @Html.HiddenFor(model => Model.ReservationInfo.EndDATE)
                        </div>
                        @Html.ValidationMessageFor(model => model.ReservationInfo.EndDATEDescription, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-4">
                <div class="form-group">
                    <span class="form_label">Възрастни</span>
                    <div class="form-group">
                        <div class="form-group">
                            @Html.EditorFor(model => model.ReservationInfo.Adults, new { htmlAttributes = new { @class = "form-control", min = 0, @readonly = true } })
                            @Html.ValidationMessageFor(model => model.ReservationInfo.Adults, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-sm-4">
                <div class="form-group">
                    <span class="form_label">Деца</span>
                    <div class="form-group">
                        <div class="form-group">
                            @Html.EditorFor(model => model.ReservationInfo.Kids, new { htmlAttributes = new { @class = "form-control", min = 0, @readonly = true } })
                            @Html.ValidationMessageFor(model => model.ReservationInfo.Kids, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-sm-4">
                <div class="form-group">
                    <span class="form_label">Брой стай</span>
                    <div class="form-group">
                        <div class="form-group">
                            @Html.EditorFor(model => model.ReservationInfo.Rooms, new { htmlAttributes = new { @class = "form-control", min = 1, @readonly = true } })
                            @Html.ValidationMessageFor(model => model.ReservationInfo.Rooms, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-6">
                <div class="form-group">
                    <span class="form_label">Направил резервация</span>
                    @Html.EditorFor(m => m.ReservationInfo.RsvnMaker, new { htmlAttributes = new { @class = "form-control", @type = "text", @readonly = true } })
                </div>
            </div>
            <div class="col-6">
                <div class="form-group">
                    <span class="form_label">Брой нощувки</span>
                    @Html.EditorFor(m => m.ReservationInfo.Nights, new { htmlAttributes = new { @class = "form-control", @type = "text", @readonly = true } })
                </div>
            </div>
        </div>
        @Html.HiddenFor(m => m.ReservationInfo.TotalPrice)
    </div>

    for (int index = 0; index < Model.RoomList.Count; index++)
    {
        <br />
        @Html.HiddenFor(m => m.RoomList[index].IsMainRoom);
        var room = index + 1;

        if (index == 0)
        {

            <div class="container border ">
                <br />
                <h5 class="text-center">Информация относно стая номер @room</h5>
                <div class="row">
                    <div class="col">
                        <label>Изберете тип стая</label>
                        <div class="form-group">
                            @Html.DropDownListFor(m => m.RoomList[index].RoomType, Model.RoomList[index].RoomTypeList, new
                       {@class = "form-control invent roomtype", @id = "roomTypeDropDownList" + index})
                            @Html.ValidationMessageFor(m => m.RoomList[index].RoomType, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <label>Описание на стая</label>
                        <div class="form-group">
                            @Html.DropDownListFor(m => m.RoomList[index].RoomView, Model.RoomList[index].RoomViewList, new
                       {@class = "form-control roomview",
                           @id = "roomViewDropDownList" + index})
                            @Html.ValidationMessageFor(m => m.RoomList[index].RoomView, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <label>Изберете етаж</label>

                        @Html.DropDownListFor(m => m.RoomList[index].RoomFloor, Model.RoomList[index].RoomFloorList, "Изберете етаж", new{@class = "form-control roomlevel",
                       @id = "roomLevelDropDownList" + index})
                        @Html.ValidationMessageFor(m => m.RoomList[index].RoomFloor, "", new { @class = "text-danger" })
                    </div>
                    <div class="col">
                        <label>Изберете номер на стая</label>
                        @Html.DropDownListFor(m => m.RoomList[index].RoomID, Model.RoomList[index].RoomIDList, "Изберете стая", new{@class = "form-control roomid",
                       @id = "roomIdDropDownList" + index})
                        @Html.ValidationMessageFor(m => m.RoomList[index].RoomID, "", new { @class = "text-danger" })
                    </div>
                </div>
                <br />
            </div>
        }
        else
        {

            <div class="container border ">
                <h5 class="text-center">Информация относно стая номер @room</h5>
                <div class="row">
                    <div class="col">
                        <label>Изберете тип стая</label>
                        @Html.DropDownListFor(m => m.RoomList[index].RoomType, Model.RoomList[index].RoomTypeList, "Изберете тип стая", new{@class = "form-control invent roomtype",
                       @id = "roomTypeDropDownList" + index})
                        @Html.ValidationMessageFor(m => m.RoomList[index].RoomType, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <label>Изберете изглед стая</label>
                        @Html.DropDownListFor(m => m.RoomList[index].RoomView, Model.RoomList[index].RoomViewList, "Изберете изглед на стая", new{@class = "form-control roomview",
                       @id = "roomViewDropDownList" + index})
                        @Html.ValidationMessageFor(m => m.RoomList[index].RoomView, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <label>Изберете етаж</label>
                        @Html.DropDownListFor(m => m.RoomList[index].RoomFloor, Model.RoomList[index].RoomFloorList, "Изберете етаж", new{@class = "form-control roomlevel",
                       @id = "roomLevelDropDownList" + index })
                        @Html.ValidationMessageFor(m => m.RoomList[index].RoomFloor, "", new { @class = "text-danger" })
                    </div>
                    <div class="col">
                        <label>Изберете номер на стая</label>
                        @Html.DropDownListFor(m => m.RoomList[index].RoomID, Model.RoomList[index].RoomIDList, "Изберете стая", new{@class = "form-control roomid",
                       @id = "roomIdDropDownList" + index})
                        @Html.ValidationMessageFor(m => m.RoomList[index].RoomID, "", new { @class = "text-danger" })
                    </div>
                </div>
                <br />
            </div>
        }
    }

    for (int j = 0; j < Model.GuestList.Count; j++)
    {
        @Html.HiddenFor(m => m.GuestList[j].IsMainGuest);
        var text = "";
        var k = j + 1;
        if (j == 0)
        {
            text = "Въведете вашите данни";
        }
        else
        {
            text = "Въведете данни относно гост номер " + k;
        }
        <br />
        <div class="container border ">
            <br />
            <h5 class="text-center">@text</h5>
            <div class="row">
                <div class="col">
                    <label>Име</label>
                    @Html.EditorFor(m => m.GuestList[j].FirstName, new { htmlAttributes = new { @class = "form-control", @type = "text", @placeholder = "Име" } })
                    @Html.ValidationMessageFor(m => m.GuestList[j].FirstName, "", new { @class = "text-danger" })
                </div>
                <div class="col">
                    <label>Презиме</label>
                    @Html.EditorFor(m => m.GuestList[j].LastName, new { htmlAttributes = new { @class = "form-control", @type = "text", @placeholder = "Презиме" } })
                </div>
                <div class="col">
                    <label>Фамилия</label>
                    @Html.EditorFor(m => m.GuestList[j].FamilyName, new { htmlAttributes = new { @class = "form-control", @type = "text", @placeholder = "Фамилия" } })
                    @Html.ValidationMessageFor(m => m.GuestList[j].FamilyName, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <label>Тип гост</label>
                    @Html.EnumDropDownListFor(m => m.GuestList[j].PersonType, "Изберете тип", new { @class = "form-control guesttype", @id = "guestType" + j })
                    @Html.ValidationMessageFor(m => m.GuestList[j].PersonType, "", new { @class = "text-danger" })
                </div>
                <div class="col">
                    <label>Възраст</label>
                    @Html.EnumDropDownListFor(m => m.GuestList[j].PersonAge, "Изберете възраст", new { @class = "form-control guestview", @id = "guestView" + j })
                    @Html.ValidationMessageFor(m => m.GuestList[j].PersonAge, "", new { @class = "text-danger" })
                </div>
                <div class="col">
                    <label>Пол</label>
                    @Html.EnumDropDownListFor(m => m.GuestList[j].Gender, "Изберете пол", new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.GuestList[j].Gender, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <label>Телефонен номер</label>
                    <div class="form-row">
                        @Html.EditorFor(m => m.GuestList[j].PhoneNumber, new { htmlAttributes = new { @class = "form-control", @type = "text", @placeholder = "+359...." } })
                        <small id="phoneHelpInline" class="text-muted">
                            Моля пишете си номера с +359 отпред...
                        </small>
                    </div>
                </div>
                <div class="col">
                    <label>ЕГН</label>
                    <div class="form-row">
                        @Html.EditorFor(m => m.GuestList[j].EGN, new { htmlAttributes = new { @class = "form-control", @type = "text", @placeholder = "ЕГН" } })
                        @Html.ValidationMessageFor(m => m.GuestList[j].EGN, "", new { @class = "text-danger" })
                        <small id="egnHelpInline" class="text-muted">
                            ЕГН
                        </small>
                    </div>
                </div>
                <div class="col">
                    <label>Дата на раждане</label>
                    <div class="form-row">
                        @Html.EditorFor(model => model.GuestList[j].BirthDate, new { htmlAttributes = new { @class = "form-control birthdate", @placeholder = "Дата на раждане" } })
                        @Html.ValidationMessageFor(m => m.GuestList[j].BirthDate, "", new { @class = "text-danger" })
                        <small id="birthDateHelpInline" class="text-muted">
                            Дата на раждане
                        </small>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <label>Стая</label>
                    @Html.DropDownListFor(m => m.GuestList[j].GuestRoomID, Model.GuestList[j].GuestRoomIDList, "Изберете номер на стая", new{@class = "form-control guestroomid",
                       @id = "guestRoomId" + j})
                    @Html.ValidationMessageFor(m => m.GuestList[j].GuestRoomID, "", new { @class = "text-danger" })
                </div>
            </div>
            <br />
        </div>

    }
    <br />
    <div class="container">
        <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-3">
                <div class="form-btn">
                    <input class="submit-btn btn btn-outline-danger btn-lg btn-block" id="submitRsvn" type="button" value="Направи резервация" />
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-btn">
                    <input class="submit-btn btn btn-outline-success btn-lg btn-block" type="submit" name="button" value="Към търсачка" />
                </div>
            </div>
            <div class="col-md-3"></div>
        </div>
        <br />
    </div>
    <br />
    <div id="messageBox" style="display:none">
        @if (Model.RoomList.Count == 1)
        {
            <p class="text-center">
                Стаята която избрахте в момента е налична.
                Побързайте да финализирате вашата резервация, преди някои да го направи преди вас.
                Ще бъде изчислена цената, която трябва да заплатите в срок от 5 дни.
            </p>
            <p class="text-center">Продължи?</p>
        }
        else
        {
            <p class="text-center">
                Стаите които избрахте в момента са налични.
                Побързайте да финализирате вашата резервация, преди някои да го направи преди вас.
                Ще бъде изчислена цената, която трябва да заплатите в срок от 5 дни.
            </p>
            <p class="text-center">Продължи?</p>
        }

    </div>

    <div id="validationFalse" style="display:none">
        @if (Model.RoomList.Count == 1)
        {
            <p class="text-center">
                Стаята която избрахте, в момента беше запазена от друг.
                Съжаляваме за случилото се. Моля изберете друга стая.
            </p>
            <p class="text-center">Ще направим всичко възможно да си намерите стая която ве устройва.</p>
        }
        else
        {
            <p class="text-center">
                Една или повече от стаите които запазихте, в момента бяха запазени от друг.
                Съжаляваме за случилото се. Моля изберете други стаи.
            </p>
            <p class="text-center">Ще направим всичко възможно да си намерите стая която ве устройва.</p>
        }

    </div>

    <div id="roomsNotSelected" style="display:none">
        @if (Model.RoomList.Count == 1)
        {
            <p class="text-center">
                Моля първо изберете номер на стая.
            </p>
        }
        else
        {
            <p class="text-center">
                Моля, изберете стаи в които искате да гостувате.
            </p>
        }

    </div>
}

我正在尝试进行的验证是在来宾模式下进行的,即:

public class Guest
    {
        public int? GusetID { get; set; }
        public string ReservationID { get; set; }
        [Required(ErrorMessage = "Въведете име")]
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Required(ErrorMessage = "Въведете семейно име")]
        public string FamilyName { get; set; }
        public string PhoneNumber { get; set; }
        [EnumDataType(typeof(PersonType), ErrorMessage = "Въведете тип гост")]
        public PersonType PersonType { get; set; }
        [EnumDataType(typeof(PersonAge), ErrorMessage = "Въведете възраст")]
        public PersonAge PersonAge { get; set; }
        [EnumDataType(typeof(Gender), ErrorMessage = "Въведете пол")]
        public Gender Gender { get; set; }
        [Required(ErrorMessage = "Полето ЕГН не може да бъде празно")]
        [Remote("IsCorrectEGN", "Reservation", HttpMethod ="POST", ErrorMessage = "Въведете правилно ЕГН.")]
        public string EGN { get; set; }
        [Required(ErrorMessage = "Въведете дата на раждане")]
        public DateTime? BirthDate { get; set; }
        [Required(ErrorMessage ="Въведете номер на стая")]
        [Remote("CheckPersonAge", "Reservation", HttpMethod ="POST", ErrorMessage = "Възраста която въведохте, не съответсва с тип гост.")]
        public int? GuestRoomID { get; set; }
        public char? IsMainGuest { get; set; }

        public string PersonTypeDescription { get; set; }
        public string PersonAgeDescription { get; set; }
        public string PersonGenderDescription { get; set; }

        public IEnumerable<SelectListItem> PersonTypeList { get; set; }
        public IEnumerable<SelectListItem> PersonAgeList { get; set; }
        public IEnumerable<SelectListItem> PersonGenderList { get; set; }
        public IEnumerable<SelectListItem> GuestRoomIDList { get; set; }
    }

验证代码位于ReservationController中:

public JsonResult IsCorrectEGN(ReservationVM Reservation)
        {
            Reservation
            string EGN = null;
            string[] ListEGN = new string[Reservation.GuestList.Count];

            for (int index = 0; index < Reservation.GuestList.Count; index++)
            {
                EGN = Reservation.GuestList[index].EGN;
                //ListEGN[index] = Reservation.GuestList[index].EGN;


            }

            return Json(CheckEGN(EGN), JsonRequestBehavior.AllowGet);
        }

        public bool CheckEGN(string EGN)
        {
            DbManager db = new DbManager();
            int result = db.CheckIfEGNISValid(EGN);
            bool isValidEgn = false;

            if (result == 1)
                isValidEgn = true;

            return isValidEgn;
        }

并且CheckEGN(param)调用db方法,该方法将EGN发送到Oracle db,如果正确则返回1,如果错误则返回0。 DB方法如下:

public int CheckIfEGNISValid(string egn)
        {

            OracleCommand cmd = new OracleCommand("", GetDBConnection());

            cmd.CommandType = CommandType.Text;

            cmd.BindByName = true;

            OracleParameter ret = new OracleParameter();
            ret.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(ret);

            cmd.CommandText = @"select s_checks.is_EGN(:str_inp) from dual";
            cmd.Parameters.Add(GetStringParameter(egn, "str_inp"));
            //cmd.Parameters.Add(GetNotNullableDateParameter(begDate, "p_beg_date"));
            //cmd.Parameters.Add(GetNotNullableDateParameter(endDate, "p_end_date"));
            //cmd.ExecuteNonQuery();
            ret.Value = cmd.ExecuteScalar();
            closeDBConnection();

            var result = Convert.ToInt32(ret.Value.ToString());

            return result;

        }

如果我处理简单的数据,我理解远程验证的概念是MVC。 我所说的简单数据并不是指列表等。 这里的问题是,我可以有X个客人,我需要检查他们是否输入了有效的PersonID(EGN)。 到目前为止,我的代码只适用于第一个客人。 对于第2次,第3次。。。第n次,ReservationVM为空。 因此没有数据通过Ajax从视图传递到控制器。

我怎样才能使我的验证检查每一位客人。 我愿意接受任何建议。 我对ASP.NET还是新手,还有很多东西要学。


共1个答案

匿名用户

我想您忘记在视图中添加这些脚本了

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.min.js"></script>

这个链接可能对你有帮助