javascript – DevExtreme dxGrid查找列表单显示ID而不是DisplayExpr

前端之家收集整理的这篇文章主要介绍了javascript – DevExtreme dxGrid查找列表单显示ID而不是DisplayExpr前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用DevExtreme dxGrid来显示和编辑用户的数据,我有一个查阅列来选择用户部门.
网格中的数据正确显示,但是在我按下编辑按钮并弹出窗体显示查找字段后,显示部门的id值,而不是DisplayExpr中指定的值,但是当我单击下拉列表时,正确显示的值.

我在DevExpress网站上搜索了很多,并尝试了他们所说的关于数据源和JS之间类型不匹配的所有内容,但没有任何效果.

csHTML代码

@(Html.DevExtreme().DataGrid().ID("gridContainer")
            .DataSource(d => d.WebApi().Controller("UsersApi").Key("Id").LoadAction("GetUsers").UpdateAction("Put"))
            .AllowColumnReordering(true)
            .AllowColumnResizing(true)
            .ColumnAutoWidth(true)
            .ColumnChooser(c => c.Enabled(true))
            .GroupPanel(groupPanel => groupPanel.Visible(true))
            .OnToolbarPreparing("OnToolbarPreparing")
            .OnEditorPreparing("OnEditorPreparing")
            .Editing(e =>
            {
                e.AllowUpdating(true);
                e.Mode(GridEditMode.Popup);
            })
            .Columns(c =>
            {
                c.Add().DataField("IsActive").Caption("Active").Width("100");
                c.Add().DataField("UserName").Caption("Username").Width("120").AllowEditing(false);
                c.Add().DataField("FullName").Caption("Full Name").Width("200");
                c.Add().DataField("Email").Width("250");
                c.Add().DataField("CreatedUtc")
                    .Caption("Created")
                    .DataType(GridColumnDataType.Date)
                    .CellTemplate(new JS("created_CellTemplate"))
                    .Visible(false)
                    .ShowInColumnChooser(true)
                    .AllowEditing(false)
                    .Width("80");
                c.Add().DataField("CreatedBy").Caption("Created By").Visible(false).ShowInColumnChooser(true).AllowEditing(false).Width("120");

                c.Add().DataField("LastAccessStr")
                    .Caption("Latest Access")
                    .CellTemplate(new JS("latestAccess_CellTemplate"))
                    .CalculateSortValue("LastAccessUtc")
                    .SortOrder(SortOrder.Desc)
                    .AllowEditing(false)
                    .Width("120");

                c.Add().DataField("LastLoginStr")
                    .Caption("Latest Login")
                    .CellTemplate(new JS("latestLogin_CellTemplate"))
                    .CalculateSortValue("LastLoginUtc")
                    .AllowEditing(false).Visible(false).ShowInColumnChooser(true)
                    .Width("120");
                c.Add().DataField("LastLoginIP").Caption("Latest Login IP").AllowEditing(false).Width("150");
                c.Add().DataField("PhoneNumber").Caption("Phone").Width("150").Visible(false).ShowInColumnChooser(true);
                c.Add().DataField("Role").Width("200");
                c.Add().DataField("DepartmentId").Caption("Department").Width(200).Lookup(
                    lookup => lookup
                    .DataSource(d => d.WebApi()
                    .Controller("DepartmentsApi")
                    .LoadAction("GetDepartment")
                    .Key("Id"))
                    .DisplayExpr("Name")
                    .ValueExpr("Id")

               );
            })
            .Summary(c =>
            {
                c.TotalItems(cc => cc.Add().Column("UserName").SummaryType(SummaryType.Count));
            })
            .Paging(paging => paging.PageSize(25))
            .Pager(pager =>
            {
                pager.ShowPageSizeSelector(true);
                pager.AllowedPageSizes(new List<int> { 10,25,50 });
                pager.ShowInfo(true);
            })
            .FilterRow(filterRow => filterRow
                .Visible(false)
                .ApplyFilter(GridApplyFilterMode.Auto)
            )
            .SearchPanel(searchPanel => searchPanel
            .Visible(true)
            .Width(240)
            .Placeholder("Search...")
        )

        .RowAlternationEnabled(true)
        .OnCellPrepared("cell_prepared")
)


<script>
    function created_CellTemplate(cellElement,cellInfo) {

        var tipid = cellInfo.data.Id;
        var sitetextid = cellInfo.data.Id + "s";

        $("<div id=" + tipid + "></div><div id=" + sitetextid + "><div>").text(cellInfo.data.ElapsedTime).appendTo(cellElement);

        $("#" + tipid).dxTooltip({
            target: "#" + sitetextid,showEvent: "dxhoverstart",hideEvent: "dxhoverend",position: "top",contentTemplate: function (contentElement) {

                var utcDate = new Date(cellInfo.data.CreatedUtc);
                contentElement.html("<b>" + convertUtcToLocal(utcDate) + "</b>");
            }
        });
    }

    function last_CellTemplate(cellElement,cellValue,cellDisplayValue,tipId,cellTextId) {
        if (cellDisplayValue === 'N/A') {
            $("<div id=" + tipId + "></div>").text(cellDisplayValue).appendTo(cellElement);
        } else {
            $("<div id=" + tipId + "></div><div id=" + cellTextId + "><div>").text(cellDisplayValue).appendTo(cellElement);
            $("#" + tipId).dxTooltip({
                target: "#" + cellTextId,contentTemplate: function (contentElement) {
                    var utcDate = new Date(cellValue);
                    contentElement.html("<b>" + convertUtcToLocal(utcDate) + "</b>");
                }
            });
        }

    }

    function latestAccess_CellTemplate(cellElement,cellInfo) {
        var tipid = 'la_' + cellInfo.data.Id;
        var sitetextid = 'la_' + cellInfo.data.Id + "s";

        last_CellTemplate(cellElement,cellInfo.data.LastAccessUtc,cellInfo.data.LastAccessStr,tipid,sitetextid);
    }
    function latestLogin_CellTemplate(cellElement,cellInfo) {
        var tipid = 'll_' + cellInfo.data.Id;
        var sitetextid = 'll_' + cellInfo.data.Id + "s";

        last_CellTemplate(cellElement,cellInfo.data.LastLoginUtc,cellInfo.data.LastLoginStr,sitetextid);
    }

    function OnToolbarPreparing(e) {
        var dataGrid = e.component;
        var toolbarItems = e.toolbarOptions.items;

        toolbarItems.push({
            widget: 'dxButton',options: { icon: 'refresh',onClick: function () { dataGrid.refresh(); } },location: 'after'
        });

        toolbarItems.push({
            widget: 'dxButton',options: {
                icon: 'filter',hint: 'Show Filters',onClick: function (data) {
                    dataGrid.option('filterRow.visible',!dataGrid.option('filterRow.visible'));
                }
            },options: {
                icon: 'add',hint: 'New User',onClick: function (data) {
                    window.location.href = '/Admin/AddUser';
                }
            },location: 'after'
        });
    }

    function OnEditorPreparing(e) {
        if (e.dataField === 'Role') {
            e.cancel = true;
            var selectBox = $('<div id="role-editor"></div>').dxSelectBox({
                dataSource: "/Admin/GetAllRoles",value: e.value,onValueChanged: function (ev) {
                    e.setValue(ev.value);
                }
            });
            e.editorElement.html(selectBox);
        }
    }

    function cell_prepared(e) {
        if (e.rowType === "data" && e.column.command === "edit") {
            var isEditing = e.row.isEditing,$links = e.cellElement.find(".dx-link");

            $links.text("");

            if (isEditing) {
                $links.filter(".dx-link-save").addClass("dx-icon-save");
                $links.filter(".dx-link-cancel").addClass("dx-icon-revert");
            } else {
                $links.filter(".dx-link-edit").addClass("dx-icon-edit");
                $links.filter(".dx-link-delete").addClass("dx-icon-trash");
            }
        }
    }

</script>

departmentId列中的问题.

UsersApiController.cs代码

public class UsersApiController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IUnitOfWork _unitOfWork;

    public UsersApiController(UserManager<ApplicationUser> userManager,IUnitOfWork unitOfWork)
    {
        _userManager = userManager;
        _unitOfWork = unitOfWork;
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers()
    {
        var users = new List<Userviewmodel>();

        foreach (var user in _unitOfWork.ApplicationUsers.GetAll())
        {
            if (user.UserName.ToLower() == "admin")
                continue;
            var userRoles = await _userManager.GetRolesAsync(user);
            var userToAdd = new Userviewmodel
            {
                Id = user.Id,UserName = user.UserName,FullName = user.FullName,Email = user.Email,IsActive = user.IsActive,PhoneNumber = user.PhoneNumber,CreatedUtc = user.CreatedUtc,ElapsedTime = DateHelper.GetElapsedTime(user.CreatedUtc),Role = user.Role,LastAccessUtc = user.LastAccess,LastAccessStr = DateHelper.GetElapsedTime(user.LastAccess),LastLoginIP = user.LastLoginIP,LastLoginUtc = user.LastLogin,LastLoginStr = DateHelper.GetElapsedTime(user.LastLogin),CreatedBy = user.CreatedByUsername,DepartmentId=user.DepartmentId
            };
            users.Add(userToAdd);
        }

        return Ok(users);
    }

DepartmentsApiController.cs代码

public class DepartmentsApiController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IUnitOfWork _unitOfWork;

    public DepartmentsApiController(UserManager<ApplicationUser> userManager,IUnitOfWork unitOfWork)
    {
        _userManager = userManager;
        _unitOfWork = unitOfWork;
    }

    [HttpGet]
    public IActionResult GetDepartment()
    {
        var dep = _unitOfWork.DepartmentsRep.GetAll();

        return Ok(dep);
    }

请注意,departmentId是Guid类型.
我也尝试用字符串类型替换Gu​​id类型,问题仍然相同.我也尝试在UsersApi和DepatementsApi中使用int而不是Guid,问题仍然相同.我正在尝试这个,因为在DevExpress网站上他们因为类型不匹配而说这个问题.
我已经包含了显示问题的图像.

解决方法

首先你的示例代码有一些问题,你的DepartmentsApiController继承自Controller但是返回Ok(),它应该继承自ApiController,其次,你的GetDepartment动作返回一个IActionResult,它应该返回一个IHttpActionResult

现在,经过这些考虑后,您的问题就出现了问题,问题在于您的GetDepartment Action,它看起来像这样

[HttpGet]
public IActionResult GetDepartment()
{
    var dep = _unitOfWork.DepartmentsRep.GetAll();

    return Ok(dep);
}

但应该看起来像这样

[HttpGet]
 public HttpResponseMessage GetDepartment(DataSourceLoadOptions oadOptions)
{
            var dep = _unitOfWork.DepartmentsRep.GetAll();

            return Request.CreateResponse(DataSourceLoader.Load(dep,loadOptions));
}

在这里,您可以看到DevExpress官方示例代码

剃刀

columns.Add()
            .DataField("ShipVia")
            .Caption("Shipping Company")
            .Lookup(lookup => lookup
                .DataSource(d => d.WebApi().Controller("GridData").LoadAction("ShippersLookup").Key("Value"))
                .ValueExpr("Value")
                .DisplayExpr("Text")
            );

API

[HttpGet]
public HttpResponseMessage ShippersLookup(DataSourceLoadOptions loadOptions)
{
            var lookup = from i in _nwind.Shippers
                         orderby i.CompanyName
                         select new
                         {
                             Value = i.ShipperID,Text = i.CompanyName
                         };

            return Request.CreateResponse(DataSourceLoader.Load(lookup,loadOptions));
  }

猜你在找的JavaScript相关文章