jquery 如何通过 AJAX 使用数据库数据填充ASP.NETMVC4下拉列表

2guxujil  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(119)

我试图填充/填写下拉列表,但我似乎无法得到我需要的值。“员工姓名”下拉列表不会被填充,而“平台组”下拉列表会被填充。对于“员工姓名”,我使用POST,因为这个方法是由软件中的另一个视图调用的,所以我宁愿不更改它。
我尝试了所有我能做的,但值不会显示在控制台或用户界面中。我错过了什么?
机型

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("{1}{0}", 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("{1}{0}", 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;
            }
        }


另外,当我取消对“EmployeeName”的 AJAX 请求代码的注解时,“Platformgroup”将停止填充。当我回复它时,“平台组”被填充得很好。
感谢您发送编修。

3yhwsihp

3yhwsihp1#

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

**UPDATE 1:**这里是EXAMPLE代码,这就是你需要的。

相关问题