簡體   English   中英

使用視圖模型進行遠程驗證。 列出視圖模型中的屬性

[英]Remote validation with viewmodels. List properties in viewmodel

我正在嘗試對預訂 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

}

該虛擬機的視圖是:

@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。 數據庫方法如下:

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 是 null。因此沒有數據從視圖傳遞到 controller 和 AJAX。

我如何進行驗證以檢查每位客人。 我願意接受任何建議。 我還是 ASP.NET 的新手,還有很多東西要學。

所以這就是列表中第一項發生的情況,首先 EGN 到達 controller 1

第二個: 2

我想你忘了在view中添加這些腳本

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

鏈接可能對您有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM