MVC Autocomplete, чтобы не публиковать поле SearchTextId на контроллере - PullRequest
1 голос
/ 16 марта 2012

У меня есть вид, который содержит частичный вид.В рамках этого частичного представления я делаю автозаполнение, и предполагается, что оно заполняет поле Id.Когда я смотрю в инструменты разработчика, то замечаю, что есть 2 скрытых поля с одинаковым именем, одно из которых заполнено правильным значением, другое - нулем.Это ноль, который отправляется обратно, и это неправильно.

Так что мой взгляд выглядит как

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.master" 
Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.PayrollViewModel>" %>
<%@ Import Namespace="SHP.Helpers" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Payroll
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm("Payroll", "Payroll", FormMethod.Post, new { id = "frmPayroll" }))
       {%>
        <%: Html.AntiForgeryToken()%>
        <%: Html.ValidationSummary(true)%>
    <fieldset>
        <legend>Payroll</legend>
            <%  Html.RenderPartial("EmployeeSelection", Model.HolidayYearViewModel); %>
        </fieldset>
              <%} %>

.,.

Мой частичный вид выглядит так:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.Models.HolidayYearViewModel>" %>

        <table class="groupBorder">
            <tr>
                <th>SelectYear</th>
                <th colspan="2">Enter 2 or more characters for "<%: Html.LabelFor(model => model.SearchText)%>" and select from the list.</th>
            </tr>
            <tr>
                <td><%: Html.DropDownListFor(model => model.SelectedHolidayYearId, Model.SelectListHolidayYear) %></td>
                <td><%: Html.LabelFor(model => model.SearchText)%></td>
                <td><%: Html.AutocompleteFor(model => model.SearchText, controller: "Payroll",
                                            minLength: 2, maxResults: 10,
                                            htmlAttributes: new { style = "color:purple; width:500px;" })%>
                                <%: Html.HiddenFor(model => model.SearchTextId)%>
                </td>
            </tr>
            <tr>
                <td colspan="2"></td>
                <td><input type="submit" value="Get leave for this person" id="btnSubmit" /></td>
            </tr>
        </table>

Мой контроллер выглядит так:

/// Заработная плата - пользователь вводит сотруднику диапазон дат, чтобы получить детали его отпуска,/// /// Представление, позволяющее пользователю вводить сотрудника и диапазон дат ///, с которого они могут просматривать свои выходные./// [HttpGet] [Authorize (Roles = "Администратор, AdminAccounts, ManagerAccounts, ManagerIT")] public ActionResult Payroll () {return SessionObjects.PayrollSelectedEmployeeId == 0?this.View (new PayrollViewModel ()): this.View (new PayrollViewModel (SessionObjects.PayrollSelectedEmployeeId));}

/// <summary> Payroll - This view shows a list of all the leave an employee has taken 
/// within the specified time period.
/// </summary>
/// <param name="pvm">
/// The pvm - payroll view model contains the above list.
/// </param>
/// <returns>A view of the leave dates for the specified employee.
/// </returns>
[HttpPost]
[Authorize(Roles = "Administrator, AdminAccounts, ManagerAccounts, ManagerIT")]
public ActionResult Payroll(PayrollViewModel pvm)
{
    if (ModelState.IsValid)
    {
        SessionObjects.HolidayYearViewModel = pvm.HolidayYearViewModel;
        if (pvm.HolidayYearViewModel.SearchTextId > 0)
        {
            SessionObjects.PayrollSelectedEmployeeId = pvm.HolidayYearViewModel.SearchTextId;
        }

        return RedirectToAction("Payroll");
    }

    return View(pvm);
}

Автозаполнение - работает, выглядит как

public ActionResult Search(string searchText, int maxResults)
{
    var filteredEmployees =
        Employee.GetAllCurrentEmployees().Where(x =>
            x.GetName().ToLower().Contains(searchText.ToLower()))
        .Select(x => new IdTextItem { Text = x.GetAutocompleteName(), Id = x.EmployeeId })
        .Take(maxResults);
    return Json(filteredEmployees, JsonRequestBehavior.AllowGet);
}

Моя ViewModel выглядит как

   #region PayrollViewModel
    public class PayrollViewModel
    {
        [DisplayName("Period Start Date")]
        [DataType(DataType.Date)]
        [Required(ErrorMessage = "You must enter a start date")]
        public DateTime PeriodStartDate { get; set; }

        [DisplayName("Period End Date")]
        [DataType(DataType.Date)]
        [Required(ErrorMessage = "You must enter an end date")]
        public DateTime PeriodEndDate { get; set; }

        public int EmployeeId { get; set; }
        public Employee Employee { get; set; }
        public List<Leave> LeaveList { get; set; }

        public HolidayYearViewModel HolidayYearViewModel { get; set; }

        public PayrollViewModel()
        {
            this.HolidayYearViewModel = SessionObjects.HolidayYearViewModel ?? new HolidayYearViewModel();
            var holidayYear = HolidayYear.GetHolidayYearById(HolidayYearViewModel.SelectedHolidayYearId);
            this.PeriodStartDate = holidayYear.HolidayYearStartDate;
            this.PeriodEndDate = holidayYear.HolidayYearEndDate;
        }

А HolidayYearViewModel, который используется в PartialView, выглядит следующим образом;

   public class HolidayYearViewModel
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HolidayYearViewModel"/> class.
        /// </summary>
        public HolidayYearViewModel()
        {
            this.ListHolidayYear = new List<HolidayYear>();
            this.ListHolidayYear = HolidayYear.GetHolidayYearsInRange();
            this.SelectedHolidayYearId = HolidayYear.GetHolidayYearThisYear().HolidayYearId;
        }

        /// <summary>
        /// Gets or sets SelectedHolidayYearId.
        /// </summary>
        public int SelectedHolidayYearId { get; set; }

        /// <summary>
        /// Gets or sets ListHolidayYear - a list of the holiday year since the employee start Date
        /// </summary>
        public List<HolidayYear> ListHolidayYear { get; set; }

        /// <summary>
        /// Gets or sets SearchText.
        /// </summary>
        [DisplayName("Get Employee")]
        [DataType(DataType.Text)]
        public string SearchText { get; set; }

        /// <summary>
        /// Gets or sets SearchTextId.
        /// </summary>
        public int SearchTextId { get; set; }

        /// <summary>
        /// Gets SelectListHolidayYear by converting the ListHolidayYear into a select list.
        /// </summary>
        public IEnumerable<SelectListItem> SelectListHolidayYear
        {
            get
            {
                return this.ListHolidayYear.Select(item => new SelectListItem
                {
                    Text = item.HolidayYearName,
                    Value = item.HolidayYearId.ToString(),
                    Selected = item.HolidayYearId == this.SelectedHolidayYearId
                });
            }
        }
    }

Любые комментарии о том, как улучшить код, также приветствуются!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...