如何通过 ajax 使用数据库数据填充 ASP.NET MVC 4 下拉列表

Posted

技术标签:

【中文标题】如何通过 ajax 使用数据库数据填充 ASP.NET MVC 4 下拉列表【英文标题】:How to populate an ASP.NET MVC 4 dropdown with database data via ajax 【发布时间】:2021-09-08 18:06:29 【问题描述】:

我正在尝试填充/填充下拉列表,但似乎无法获得所需的值。 “员工姓名”下拉列表不会填充,而“平台组”下拉列表会填充。 对于“员工姓名”,我使用 POST,因为此方法由软件中的另一个 VIEW 调用,所以我不想更改它。

我尽我所能,但值不会显示在控制台或 UI 中。 我错过了什么?

型号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FXM.BO.ViewModels

    public class NewAffiliateViewModel
    
        public NewAffiliateViewModel()
        
        
        public int Id  get; set; 
        public string AffiliateName  get; set; 
        public string Email  get; set; 
        public int Employee  get; set; 
        public int MT4Group  get; set; 
    

查看

@model FXM.BO.ViewModels.NewAffiliateViewModel

@
    ViewBag.Title = "CreateAffiliate";
    Layout = "~/Views/Shared/_LoggedInLayout.cshtml";


<h2>Create Affiliate</h2>


@using (Html.BeginForm())

    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4 class="hidden">NewAffiliateViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new  @class = "text-danger" )
        <div class="form-group">
            @Html.LabelFor(model => model.AffiliateName, htmlAttributes: new  @class = "control-label col-md-2" )
            <div class="col-md-10">
                @Html.EditorFor(model => model.AffiliateName, new  htmlAttributes = new  @class = "form-control"  )
                @Html.ValidationMessageFor(model => model.AffiliateName, "", new  @class = "text-danger" )
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new  @class = "control-label col-md-2" )
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new  htmlAttributes = new  @class = "form-control"  )
                @Html.ValidationMessageFor(model => model.Email, "", new  @class = "text-danger" )
            </div>
        </div>

        @*<div class="form-group">
                @Html.LabelFor(model => model.Employee, htmlAttributes: new  @class = "control-label col-md-2" )
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Employee, new  htmlAttributes = new  @class = "form-control"  )
                    @Html.ValidationMessageFor(model => model.Employee, "", new  @class = "text-danger" )
                </div>
            </div>*@

        @*<div class="form-group">
                @Html.LabelFor(model => model.MT4Group, htmlAttributes: new  @class = "control-label col-md-2" )
                <div class="col-md-10">
                    @Html.EditorFor(model => model.MT4Group, new  htmlAttributes = new  @class = "form-control"  )
                    @Html.ValidationMessageFor(model => model.MT4Group, "", new  @class = "text-danger" )
                </div>
            </div>*@

        <div class="form-group">
            <label class="control-label col-md-2">
                @FXM.BO.Strings.T("employeeName") <span class="required">
                    @***@
                </span>
            </label>
            @*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*@
            <div class="col-md-10 ">
                @Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option"), new  @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" )
                <span class="help-block">
                    @FXM.BO.Strings.T("lbl_employee_description")
                </span>
            </div>
            <img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
        </div>

        <div class="form-group">
            <label class="control-label col-md-2">
                @FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
                    @***@
                </span>
            </label>
            @*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*@
            <div class="col-md-10 ">
                @Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option2"), new  @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" )
                <span class="help-block">
                    @FXM.BO.Strings.T("platform_group_description")
                </span>
            </div>
            <img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
        </div>
        @*Create button*@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
            </div>
        </div>
    </div>


<div>
    @Html.ActionLink("Back to List", "Index")
</div>


<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>


@*<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>*@
<script type="text/javascript">
    // document.ready function
    $(function () 
        refreshGroups();
        // selector has to be . for a class name and # for an ID
        $('#create-affiliate-button').click(function (e) 
            //e.preventDefault(); // prevent form from reloading page
            console.log("blahblahblah");


            var b = $("form").serialize();
            //var a = $("form").serializeArray();
            console.log("formvalues", b);

         $.ajax(
                url: "/en/AjaxUI/CreateAffiliate",
                type: "GET",
                dataType: "json",
                data: b,
            ,
       
                //error: function (jqXHR, exception) 
                //    failMessage();
                //
            );
        );
    );

    function refreshGroups() 
        var pltf = "MT4_LIVE";
        var out = $('#MT4Group');
        if (pltf != null && pltf !== "") 
            $.ajax(
                url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
                data: 
                    platform: pltf, currency: "", withId : true
                ,
                type: 'GET',
                beforeSend: function () 
                    $('#tpLoader').show();
                ,
                complete: function () 
                    $('#tpLoader').hide();
                ,
                success: function (data) 
                    populateDropDown(out, data);
                    //$('#recomandedGroup').show();
                
            );
         else 
            out.empty();
            out.append($('<option></option>').val('').html(window.defaultSelection));
        
    

    //GetEmployeesExcept - Method that populates the Dropdown for EmployeeName

    $(function() 
        $.validator.addMethod("regxPhone", function(value, element, regexpr) 
            return regexpr.test(value);
        ),
        $.validator.addMethod("regxEmail", function(value) 
            return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
        ),
        $.validator.addMethod('validEmail', function(value, element, param) 
            return valiEmailAjax($("#Email").val());
        );

        

        $('#create-affiliate-button').select2(
            theme: "bootstrap",
            ajax: 
                url: "/en/BOEmployeeAjax/GetEmployeesExcept",
                type: "POST",
                dataType: "json",
                data: function(params) 
                    return 
                        emplId: 0,
                        t: params.term
                    
                ,
                processResults: function(data, params) 
                    return  results: data 
                
            ,
            placeholder: window.selectAnotherSupervisor,
            escapeMarkup: function(markup)  return markup; ,
            minimumInputLength: 0
        );

</script>

控制器中的方法(用于员工姓名)

        [HttpPost]
        [OutputCache(CacheProfile = "Cache10mn", Location = OutputCacheLocation.Client, NoStore = true)]
        public JsonResult GetEmployeesExcept(int emplId, string t, bool searchByUserId=false)
        
            t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
            t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;

            if (!searchByUserId)
            
                return Json(CrmServices.GetAllEmployees()
                    .Where(w => w.Id != emplId && string.Format("10", w.UserDetails.Fullname, w.Id).ToLower().Contains(t.ToLower()))
                    .Select(s => new  id = s.Id, text = string.Format("1 : 0", s.UserDetails.Fullname, s.Id) ));
            
            else
            
                return Json(CrmServices.GetAllEmployees()
                    .Where(w => w.UserDetails != null && int.Parse(w.UserDetails.UserID) != emplId && string.Format("10", w.UserDetails.Fullname, w.UserDetails.UserID).ToLower().Contains(t.ToLower()))
                    .Select(s => new  id = s.UserDetails.UserID, text = string.Format("1 : 0", s.UserDetails.Fullname, s.UserDetails.UserID) ));
            
        

控制器中的方法(用于“平台组”)

        public JsonResult CreateAffiliate(NewAffiliateViewModel newAffiliateViewModel)
        
            try
            
                var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
                //SystemServices.ResendEmail(userId);
                return Json("success");

                //return Json(null, JsonRequestBehavior.DenyGet);
            
            catch (Exception e)
            
                throw e;
            
        

此外,当我取消注释“员工姓名”的 ajax 请求代码时,“平台组”将停止填充。当我回复它时,“平台组”填充得很好。

感谢您的回复。

【问题讨论】:

您的浏览器控制台有错误吗?您似乎调用了.select2(),但似乎没有将其包含在&lt;script src="...select2.js"&gt; 或其css 中。 请阅读minimal reproducible example - 理想情况下,您应该减少代码,直到只剩下与问题相关的位。似乎有很多额外的代码。例如,您提到“对员工姓名的 ajax 请求”-但在所有代码中的位置并不是很明显。提供代码很好,但在这种情况下,可能有点太多了。 感谢 freen-m 和 @Никита 的建议。我会努力实现它们。 【参考方案1】:

您需要搜索:“Select2” 这是网站https://select2.org/ 阅读指南,很简单

更新 1: 这是EXAMPLE 的代码,你需要,伙计。

【讨论】:

@TomSawyer 你需要 6.Data Sources -> Ajax 您能说得更具体一点吗?我不明白你的意思:6.Data Sources -> Ajax。谢谢 感谢您的澄清!我会查的。 @TomSawyer 好的。在该手册中,您需要 6 个步骤,然后是 AJAX 描述。在页面的顶部将是“入门 - 数据源 - Ajax(远程数据)”。等一下,我会给你 ASP 中的代码示例。 @TomSawyer 请检查更新答案。

以上是关于如何通过 ajax 使用数据库数据填充 ASP.NET MVC 4 下拉列表的主要内容,如果未能解决你的问题,请参考以下文章

通过 ajax 使用实体数据库填充下拉列表

通过ajax请求填充数组

如何使用 JSON 数据填充下拉列表作为 jQuery 中的 ajax 响应

如何使用多个 Django FBV 通过 Ajax+jQuery 捕获和保存数据

如何使用 Ajax 和 Jquery 从 PHP 数据库中提取信息,并使用该信息填充元素?

使用 JQUERY 和 AJAX 在 Laravel 分页中重新填充表数据