Html.DropDownListДля выбранного значения не отображается при обратной передаче - PullRequest
0 голосов
/ 11 мая 2011

На мой взгляд, есть 5 выпадающих списков.Первый заполняется, когда пользователь впервые попадает на страницу.Затем остальные раскрывающиеся списки заполняются в зависимости от того, что они выбирают из раскрывающихся списков.Привязка выпадающих работает нормально .. без проблем.По сути, на странице есть кнопка отправки, которая отображает результаты значений, выбранных из выпадающих списков.Проблема на HttpPost, все, что было выбрано из выпадающего списка, они исчезают.Другая вещь, в то время как я продолжаю изменять выбранное значение и отправляю, они появляются.

Например, я выбираю значения в каждом из выпадающих меню.Сделайте отправку, результаты отобразятся, и только первое показывает выбранное значение.Остальные ушли.Затем в то же время я выбираю оставшиеся значения, делаю отправку, теперь появляются первое и второе, а остальные исчезают.Я повторяю то же самое, делаю постбэк, появляются 1-й, 2-й и 3-й номера, а остальные исчезаютНе уверен, что здесь происходит.Дайте мне знать, если мне нужно обновить этот пост с моим кодом.Просто хотел проверить, есть ли быстрое исправление, прежде чем публиковать то, что я сделал.

    <script type="text/javascript">
    $(document).ready(function () {
        $('select#NationId').change(function () {
            var nationId = $(this).val();
            $.ajax({
                url: 'LoadAreas',
                type: 'POST',
                data: JSON.stringify({ nationId: nationId }),
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    $('select#AreaId').get(0).options.length = 0;
                    $('select#AreaId').append('<option value="0">Select All</option>');
                    $.each(data, function (val, Areas) {
                        $('select#AreaId').append('<option value="' + Areas.Id + '">' + Areas.Name + '</option>');
                    });
                }
            });
        });
        $('select#AreaId').change(function () {
            var areaId = $(this).val();
            $.ajax({
                url: 'LoadDistricts',
                type: 'POST',
                data: JSON.stringify({ areaId: areaId }),
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    $('select#DistrictId').get(0).options.length = 0;
                    $('select#DistrictId').append('<option value="0">Select All</option>');
                    $.each(data, function (val, Districts) {
                        $('select#DistrictId').append('<option value="' + Districts.Id + '">' + Districts.Name + '</option>');
                    });
                }
            });
        });
        $('select#DistrictId').change(function () {
            var districtId = $(this).val();
            $.ajax({
                url: 'LoadTerritoryManagers',
                type: 'POST',
                data: JSON.stringify({ districtId: districtId }),
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    $('select#TMId').get(0).options.length = 0;
                    $('select#TMId').append('<option value="0">Select All</option>');
                    $.each(data, function (val, TMManagers) {
                        $('select#TMId').append('<option value="' + TMManagers.Id + '">' + TMManagers.Name + '</option>');
                    });
                }
            });
        });
        $("#TMId").change(function () {
            var tmId = $(this).val();
            $.ajax({
                url: 'LoadDealers',
                type: 'POST',
                data: JSON.stringify({ tmId: tmId }),
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    $("#ChannelId").get(0).options.length = 0;
                    $("#ChannelId").append('<option value="0">Select All</option>');
                    $.each(data, function (val, SurveyDealers) {
                        $("#ChannelId").append('<option value="' + SurveyDealers.Id + '">' + SurveyDealers.DealerId + '</option>');
                    });
                }
            });
        });
    });
</script>
@using (Html.BeginForm())
{
    <div style="width: 100%; font-size: 14px; font-family: Arial, Helvetica, sans-serif;">
        <div align="right" style="padding-top: 10px;">
            @Html.ActionLink("Back to Reports page", "Index", "Reports/Customers", new { area = "" }, new { @class = "PremireButton" })
        </div>
        <h3  style="background-color: #CC0000; color: #fff; font-size: 1.5em;">
            Customer Survey Report</h3>
        <table width="50%" cellpadding="0" cellspacing="0" style="padding: 10px 0 5px 5px;">
            @if (Model.ShowNational)
            {
                <tr>
                    <td style="padding: 5px 0 5px 5px;">
                        <b>Select a Country:</b>
                    </td>
                    <td style="padding: 5px 0 5px 5px;">@Html.DropDownListFor(m => m.NationId, Model.NationalChannelGroups, "Select All")
                    </td>
                </tr>
            }
            @if (Model.ShowArea)
            {
                <tr>
                    <td style="padding: 5px 0 5px 5px;">
                        <b>Select an Area:</b>
                    </td>
                    <td style="padding: 5px 0 5px 5px;">@Html.DropDownListFor(m => m.AreaId, Model.AreaChannelGroups, "Select All")
                    </td>
                </tr>
            }
            @if (Model.ShowDistrict)
            {
                <tr>
                    <td style="padding: 5px 0 5px 5px;">
                        <b>Select a District:</b>
                    </td>
                    <td style="padding: 5px 0 5px 5px;">@Html.DropDownListFor(m => m.DistrictId, Model.DistrictChannelGroups, "Select All")
                    </td>
                </tr>
            }
            @if (Model.ShowTM)
            {
                <tr>
                    <td style="padding: 5px 0 5px 5px;">
                        <b>Select a TM:</b>
                    </td>
                    <td style="padding: 5px 0 5px 5px;">@Html.DropDownListFor(m => m.TMId, Model.TMChannelGroups, "Select All")
                    </td>
                </tr>
            }
            <tr>
                <td style="padding: 5px 0 5px 5px;">
                    <b>Select a Dealer:</b>
                </td>
                <td style="padding: 5px 0 5px 5px;">@Html.DropDownListFor(m => m.ChannelId, Model.Channels, "Select All")
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Submit" id="Submit" class="PremierSubmitButton" />
                </td>
            </tr>
        </table>
        @if (Model.ShowCustomerReport)
        {
        if (Model.Report.Count() > 0)
        {
            <table id="SurveyResponse" width="100%" cellpadding="0" cellspacing="0" style="font-size: 11px;">
                <thead>
                    <tr class="header">
                        <td style="padding: 2px 2px 2px 2px;">
                            Dealer #
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            District
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            TM
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Survey Code
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            First Name
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Last Name
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Address
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            City
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            State
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Postal Code
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Phone
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Mail Sent
                        </td>
                        <td style="padding: 2px 2px 2px 2px;">
                            Email Sent
                        </td>
                    </tr>
                </thead>
                <tbody>
                    @{bool alternate = false;}
                    @foreach (var tr in Model.Report)
                    {
                        <tr @(alternate ? "class=alternate" : "")>
                            <td style="padding: 2px 2px 2px 2px;">
                                @tr.DealerId
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">
                                @tr.District
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.TM
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.SurveyCode
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.FirstName
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.LastName
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.Address
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.City
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.State
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.PostalCode
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@tr.Phone
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@(tr.MailSent.HasValue ? @tr.MailSent.Value.ToShortDateString() : String.Empty)
                            </td>
                            <td style="padding: 2px 2px 2px 2px;">@(tr.DateCompleted.HasValue ? @tr.DateCompleted.Value.ToShortDateString() : String.Empty)
                            </td>
                        </tr>
                           alternate = !alternate;
                    }
                </tbody>
            </table>
        }
        else
        {
            <text>There are no records to display</text>
        }
       }
    </div>
}

Вот мой HttpPost

[HttpPost]
    public ActionResult CustomerReport(AreaManagerModel model)
    { 
         //Display Result here
         LoadDropDowns(model);
         return View("CustomerReport", model);
    }

private void LoadDropDowns(AreaManagerModel model)
    {
        var user = db.Users.Find(SessionHandler.CurrentUser.UserId);
        model.TMChannelGroups = new List<SelectListItem>();
        model.Channels = new List<SelectListItem>();
        model.AreaChannelGroups = new List<SelectListItem>();
        model.NationalChannelGroups = new List<SelectListItem>();
        model.DistrictChannelGroups = new List<SelectListItem>();

        var _signedInChannelGroupId = from s in user.ChannelGroups
                                      select s;
        if (_signedInChannelGroupId.Count() > 0)
            model.LoggedChannelGroupId = _signedInChannelGroupId.Select(m => m.ChannelGroupId).First();

        var org = (from o in user.ManagedOrganizations
                   //where o.OrganizationId == 4
                   where o.OrganizationId == 8
                   select o).FirstOrDefault();
        if (org != null || user.IsSuperUser)
        {
            model.ShowNational = true;
            model.ShowArea = true;
            model.ShowDistrict = true;
            model.ShowTM = true;

            model.NationalChannelGroups = from i in db.ChannelGroups
                                          //where i.ChannelGroupTypeId == 4
                                          where i.ChannelGroupTypeId == 6
                                          select new SelectListItem()
                                          {
                                              Text = i.Name,
                                              Value = SqlFunctions.StringConvert((double)i.ChannelGroupId)
                                          };
            if (model.NationId != 0)
            {
                var ngroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                              //where g.ChannelGroupTypeId == 4
                              where g.ChannelGroupTypeId == 6
                              select g).FirstOrDefault();
                if (ngroup != null)
                {
                    model.AreaChannelGroups = from i in ngroup.Children
                                              select new SelectListItem()
                                              {
                                                  Text = i.Name,
                                                  Value = i.ChannelGroupId.ToString()
                                              };
                }
                var agroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                              where g.ChannelGroupTypeId == 1
                              select g).FirstOrDefault();
                if (agroup != null)
                {
                    model.DistrictChannelGroups = from i in agroup.Children
                                                  select new SelectListItem()
                                                  {
                                                      Text = i.Name,
                                                      Value = i.ChannelGroupId.ToString()
                                                  };
                }
                var dgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                              where g.ChannelGroupTypeId == 2
                              select g).FirstOrDefault();
                if (dgroup != null)
                {
                    model.TMChannelGroups = from i in dgroup.Children
                                            select new SelectListItem()
                                            {
                                                Text = i.Name,
                                                Value = i.ChannelGroupId.ToString()
                                            };
                }
                var tgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                              where g.ChannelGroupTypeId == 3
                              select g).FirstOrDefault();
                if (tgroup != null)
                {
                    model.Channels = from i in tgroup.GetAllChannels()
                                     select new SelectListItem()
                                     {
                                         Text = i.ExternalChannelId,
                                         Value = i.ChannelId.ToString()
                                     };
                }
            }
        }
        else
        {
            var ngroup = (from g in user.ChannelGroups
                          //where g.ChannelGroupTypeId == 4
                          where g.ChannelGroupTypeId == 6
                          select g).FirstOrDefault();
            if (ngroup != null)
            {
                model.ShowNational = false;
                model.ShowArea = true;
                model.ShowDistrict = true;
                model.ShowTM = true;

                model.AreaChannelGroups = from i in ngroup.Children
                                          select new SelectListItem()
                                          {
                                              Text = i.Name,
                                              Value = SqlFunctions.StringConvert((double)i.ChannelGroupId)
                                          };
                if (model.AreaId != 0)
                {
                    var agroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                                  where g.ChannelGroupTypeId == 1
                                  select g).FirstOrDefault();
                    if (agroup != null)
                    {
                        model.DistrictChannelGroups = from i in agroup.Children
                                                      select new SelectListItem()
                                                      {
                                                          Text = i.Name,
                                                          Value = i.ChannelGroupId.ToString()
                                                      };
                    }
                    var dgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                                  where g.ChannelGroupTypeId == 2
                                  select g).FirstOrDefault();
                    if (dgroup != null)
                    {
                        model.TMChannelGroups = from i in dgroup.Children
                                                select new SelectListItem()
                                                {
                                                    Text = i.Name,
                                                    Value = i.ChannelGroupId.ToString()
                                                };
                    }
                    var tgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                                  where g.ChannelGroupTypeId == 3
                                  select g).FirstOrDefault();
                    if (tgroup != null)
                    {
                        model.Channels = from i in tgroup.GetAllChannels()
                                         select new SelectListItem()
                                         {
                                             Text = i.ExternalChannelId,
                                             Value = i.ChannelId.ToString()
                                         };
                    }
                }
            }
            else
            {
                var agroup = (from g in user.ChannelGroups
                              where g.ChannelGroupTypeId == 1
                              select g).FirstOrDefault();
                if (agroup != null)
                {
                    model.ShowNational = false;
                    model.ShowArea = false;
                    model.ShowDistrict = true;
                    model.ShowTM = true;
                    model.DistrictChannelGroups = from i in agroup.Children
                                                  select new SelectListItem()
                                                  {
                                                      Text = i.Name,
                                                      Value = i.ChannelGroupId.ToString()
                                                  };
                    if (model.DistrictId != 0)
                    {
                        var dgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                                      where g.ChannelGroupTypeId == 2
                                      select g).FirstOrDefault();
                        if (dgroup != null)
                        {
                            model.TMChannelGroups = from i in dgroup.Children
                                                    select new SelectListItem()
                                                    {
                                                        Text = i.Name,
                                                        Value = i.ChannelGroupId.ToString()
                                                    };
                        }
                        var tgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                                      where g.ChannelGroupTypeId == 3
                                      select g).FirstOrDefault();
                        if (tgroup != null)
                        {
                            model.Channels = from i in tgroup.GetAllChannels()
                                             select new SelectListItem()
                                             {
                                                 Text = i.ExternalChannelId,
                                                 Value = i.ChannelId.ToString()
                                             };
                        }
                    }
                }
                else
                {
                    var dgroup = (from g in user.ChannelGroups
                                  where g.ChannelGroupTypeId == 2
                                  select g).FirstOrDefault();
                    if (dgroup != null)
                    {
                        model.ShowNational = false;
                        model.ShowArea = false;
                        model.ShowDistrict = false;
                        model.ShowTM = true;
                        model.TMChannelGroups = from i in dgroup.Children
                                                select new SelectListItem()
                                                {
                                                    Text = i.Name,
                                                    Value = i.ChannelGroupId.ToString()
                                                };
                        if (model.TMId != 0)
                        {
                            var tgroup = (from g in SessionHandler.CurrentContext.ChannelGroups
                                            where g.ChannelGroupTypeId == 3
                                            select g).FirstOrDefault();
                        if (tgroup != null)
                        {
                            model.Channels = from i in tgroup.GetAllChannels()
                                             select new SelectListItem()
                                             {
                                                 Text = i.ExternalChannelId,
                                                 Value = i.ChannelId.ToString()
                                             };
                        }
                        }
                    }
                    else
                    {
                        var tgroup = (from g in user.ChannelGroups
                                      where g.ChannelGroupTypeId == 3
                                      select g).FirstOrDefault();
                        if (tgroup != null)
                        {
                            model.ShowNational = false;
                            model.ShowArea = false;
                            model.ShowDistrict = false;
                            model.ShowTM = false;
                            model.Channels = from i in tgroup.GetAllChannels()
                                             select new SelectListItem()
                                             {
                                                 Text = i.ExternalChannelId,
                                                 Value = i.ChannelId.ToString()
                                             };
                        }
                    }
                }
            }
        }
    }

ОБНОВЛЕНИЕ:

[HttpPost]
    public ActionResult LoadAreas(int nationId)
    {
        var _Areas = (from c in SessionHandler.CurrentContext.ChannelGroups
                      join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
                      where cgt.Name == "Area" && c.ParentChannelGroupId == nationId
                      select new AreaName() { Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);

        if (_Areas == null)
            return Json(null);
        List<AreaName> managers = (List<AreaName>)_Areas.ToList();

        return Json(managers);
    }
    [HttpPost]
    public ActionResult LoadDistricts(int areaId)
    {
        var _Districts = (from c in SessionHandler.CurrentContext.ChannelGroups
                    join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
                    where cgt.Name == "District" && c.ParentChannelGroupId == areaId
                    select new DistrictName() { Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);

        if (_Districts == null)
            return Json(null);

        List<DistrictName> managers = (List<DistrictName>)_Districts.ToList();
        return Json(managers);
    }
    [HttpPost]
    public ActionResult LoadTerritoryManagers(int districtId)
    {
        var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
                    join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
                    where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
                    select new TMManager() { Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);

        if (_TMS == null)
            return Json(null);

        List<TMManager> managers = (List<TMManager>)_TMS.ToList();
        return Json(managers);
    }
    [HttpPost]
    public ActionResult LoadDealers(int tmId)
    {
        var _dealers = (from c in SessionHandler.CurrentContext.Channels
                    where c.ChannelGroupId == tmId
                    select new SurveyDealer() { Id = c.ChannelId, DealerId = c.ExternalChannelId }).OrderBy(m => m.DealerId);

        if (_dealers == null)
            return Json(null);

        List<SurveyDealer> dealers = (List<SurveyDealer>)_dealers.ToList();
        return Json(dealers);
    }

1 Ответ

1 голос
/ 11 мая 2011

Давайте посмотрим ваш код View для начала, это должно помочь.

UPDATE:

Ваш код рендеринга:

DropDownListFor(m => m.TMId, Model.TMChannelGroups, "Select All")

Вынуждает DropDownBox выбрать значение «Выбрать все» независимо от значения TMId.

Полностью избавьтесь от этого последнего параметра и вместо этого измените код на стороне сервера, чтобы он возвращал объект SelectList с 0 / Select All в качестве первого SelectListItem. Затем ваш объект модели будет правильно выбирать правильную опцию из DropDownList.

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