通过AJAX成功更新<select>

时间:2017-05-29 06:54:47

标签: jquery asp.net ajax asp.net-mvc

我的视图中有一些DropdownLists 这是代码  @ Html.DropDownList(“Question1”,null,“Вопрос1”,htmlAttributes:new {@class =“form-control”,@ style =“height:40px; margin-bottom:20px;”}) 我有AJAX调用来添加问题 这是代码 &LT;脚本&GT; $(document).ready(function(){     $('#save_quest')。click(function(){        savequestion();       }); }); //Сохранениевопросавмодальномокне function savequestion(){     $就({         类型:'发布',         dataType:'Json',         数据:{             Question_new:$('#question')。val(),             答案:$('#answer')。val(),             准备:$('#prepare')。val(),             重试:$('#retries')。val(),         },         url:'@ Url.Action(“CreateNewQuestion”,“Questions”)',         成功:函数(da){             if(da.Result ===“成功”){                 $( '#myModal')隐藏()。                 emails_update();                 } else {                 alert('Error'+ da.Message);             }         },         错误:function(da){             警报( '错误');         }     }); } 如何在成功时更新DropDownList值? 感谢帮助

1 个答案:

答案 0 :(得分:0)

我附加了一个显示控制器,视图和jquery代码的示例。

查看代码

   @model IC.Models.ReportViewModel

@using (Html.BeginForm(actionName: "GetReportFilter", controllerName: "Report", method: FormMethod.Post, htmlAttributes: new { @class = "edit_form", @id = "frmStatisticsReport" }))
{
     @Html.AntiForgeryToken()
    <div class="box box-frame" style="padding-bottom: 10px;">
        <div class="box-inner" style="padding-left: 0px">
            <div class="box-caption">Search Statistical Reports</div>
            <div style="padding: 2px;">
                @Html.ValidationSummary()
            </div>
            <ul class="piped font-weight-normal">
                <li>
                    <b>Company: </b>

                            @Html.DropDownListFor(m =>  Model.CompanyId,
                                                        Model.CompanyLookupValues.Select(
                                                            c => new SelectListItem() { Value = c.CompanyId.ToString(), Text = c.CompanyName }
                                                        ),
                                                         "-- select --",
                                                        new { @class = "width-4" })
                            @Html.ValidationMessageFor(m => Model.CompanyId)
                            <text>&nbsp;&nbsp;</text>

                    <b> Report Type: </b>
                     @Html.DropDownListFor(m => Model.ReportId,
                              Model.ReportLookupValues.Select(c => new SelectListItem() { Value = c.ReportId.ToString(), Text = c.ReportName }),
                                "-- select --",
                            new { @class = "width-4" })
                        @Html.ValidationMessageFor(m => Model.ReportId)
                        &nbsp;&nbsp;
                         <input class="button-primary" type="button" id="btnGetReportFilters" value="&nbsp;&nbsp;Get Report Filters&nbsp;&nbsp;" 
                              onclick="GetFilters();" />
                </li>
            </ul>

        </div>
    </div>


}

查看使用的模型

public class ReportViewModel
    {
        [Required(ErrorMessage = "The Company is a required field")]
        [Display(Name = "Company")]
        public int CompanyId { get; set; }

        public IEnumerable<ReportCompanyViewModel> CompanyLookupValues { get; set; }

        [Required(ErrorMessage = "The Report Type is a required field")]
        [Display(Name = "Report Type")]
        public int ReportId { get; set; }

        public IEnumerable<Report> ReportLookupValues { get; set; }


    }

    public class Report
    {
        public int ReportId { get; set; }
        public string ReportName { get; set; }
    }

    public class ReportCompanyViewModel
    {
        public int CompanyId { get; set; }
        public string CompanyName { get; set; }
    }

用于填充第二个下拉列表的Jquery函数

function GetReportTypes() {
    var companyId = $("#CompanyId").val();
    if (companyId != '') {
        var url = '@Url.Action("GetReportTypes", "Report")';
        $.getJSON(url + '?companyId=' + companyId, function (data) {
            var select = $("#ReportId");
            select.empty();
            select.append($('<option/>', {
                value: '',
                text: "-- select --"
            }));

            $.each(data, function (index, itemData) {
                select.append($('<option/>', {
                    value: itemData.ReportId,
                    text: itemData.ReportName
                }));
            });
        });
    }
}

控制器代码

public ActionResult Index()
        {
            var companies = ReferenceDataService.GetFacilitiesForReport().Select(r => new ReportCompanyViewModel { CompanyId = r.Id, CompanyName = r.Name });

            ReportViewModel model = new ReportViewModel
            {
                CompanyLookupValues = companies,                
                ReportLookupValues = new List<Report>()
            };
            return View(model);
        }


 public JsonResult GetReportTypes(int companyId)
        {
            List<Report> reportTypes = new List<Report>();
            if (companyId > 0)
            {

                    reportTypes = ReferenceDataService.GetReportTypes().Select(r => new Report { ReportId = r.ReportId, ReportName = r.ReportName }).ToList();


            }

            return Json(reportTypes, JsonRequestBehavior.AllowGet); ;

        }