ajax 将参数传递给 Telerik asp.net mvc 网格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2587066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:52:28  来源:igfitidea点击:

Passing parameters to telerik asp.net mvc grid

asp.net-mvcajaxparametersgridtelerik

提问by GlobalCompe

I have a telerik asp.net mvc grid which needs to be populated based on the search criteria the user enters in separate text boxes. The grid is using ajax method to load itself initially as well as do paging.

我有一个 Telerik asp.net mvc 网格,需要根据用户在单独的文本框中输入的搜索条件进行填充。网格最初使用 ajax 方法加载自身以及进行分页。

How can one pass the search parameters to the grid so that it sends those parameters "every time" it calls the ajax method in response to the user clicking on another page to go to the data on that page?

如何将搜索参数传递给网格,以便它“每次”发送这些参数,它会调用 ajax 方法以响应用户单击另一个页面以转到该页面上的数据?

I read the telerik's user guide but it does not mention this scenario. The only way I have been able to do above is by passing the parameters to the rebind() method on client side using jquery. The issue is that I am not sure if it is the "official" way of passing parameters which will always work even after updates. I found this method on this post on telerik's site: link text

我阅读了 Telerik 的用户指南,但没有提到这种情况。我能够在上面做的唯一方法是使用 jquery 将参数传递给客户端的 rebind() 方法。问题是我不确定这是否是传递参数的“官方”方式,即使在更新后也始终有效。我在 Telerik 网站上的这篇文章中找到了这种方法:链接文本

I have to pass in multiple parameters. The action method in the controller when called by the telerik grid runs the query again based on the search parameters.

我必须传入多个参数。当被 Telerik 网格调用时,控制器中的 action 方法会根据搜索参数再次运行查询。

Here is a snippet of my code:

这是我的代码片段:

$("#searchButton").click(function() {
    var grid = $("#Invoices").data('tGrid');

    var startSearchDate = $("#StartDatePicker-input").val();
    var endSearchDate = $("#EndDatePicker-input").val();

    grid.rebind({ startSearchDate: startSearchDate ,
                    endSearchDate: endSearchDate
                });
});

回答by Craig Fisher

So according to Telerik "recommended approach is to set the arguments in the onDataBinding event".

因此,根据 Telerik “推荐的方法是在 onDataBinding 事件中设置参数”。

function onGridBinding(e) {
if (cancelGridBinding) {  
    // ...
}
else {
    var searchValue = 'something';
    e.data = { search: searchValue };
}

}

}

回答by VinnyG

For myself I use ViewModel object that I pass using jQuery and javascript object, my View is stongly typed SearchMemberModel, witch contains my search fields and I have a Textbox for every fields in my view. My databinding is on passing the Model to the controller. Then I build my object in javascript and pass it to my controller in the rebind call.

对于我自己,我使用我使用 jQuery 和 javascript 对象传递的 ViewModel 对象,我的视图是强类型的 SearchMemberModel,女巫包含我的搜索字段,并且我的视图中的每个字段都有一个文本框。我的数据绑定是将模型传递给控制器​​。然后我在 javascript 中构建我的对象并在重新绑定调用中将它传递给我的控制器。

Here's my code :

这是我的代码:

View and javascrip

查看和javascrip

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage<Enquete.Models.SearchMemberModel>" %>

<% using (Html.BeginForm()) {%>
    <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend><%: Resources.Search %></legend>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.MemberNumber) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.MemberNumber) %>
            <%: Html.ValidationMessageFor(model => model.MemberNumber) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Email) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Email) %>
            <%: Html.ValidationMessageFor(model => model.Email) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.FirstName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.FirstName) %>
            <%: Html.ValidationMessageFor(model => model.FirstName) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.LastName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.LastName) %>
            <%: Html.ValidationMessageFor(model => model.LastName) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Phone) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Phone) %>
            <%: Html.ValidationMessageFor(model => model.Phone) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Active) %>
        </div>
        <div class="editor-field">
            <%: Html.CheckBoxFor(model => model.Active) %>
            <%: Html.ValidationMessageFor(model => model.Active) %>
        </div>

        <p>
            <input type="submit" value="<%: Resources.ToSearch %>" id="btnSearch" />
        </p>
    </fieldset>

<% } %>

 <%= Html.Telerik().Grid<SerializableMember>()
                .Name("Grid")
                .Columns(colums =>
                 {
                     colums.Bound(c => c.Email).Title(Resources.Email);//.ClientTemplate("<a href=\"" + Url.Action(MVC.Admin.Edit()) + "/<#=Id#>\" ><#=Email#></a>");
                     colums.Bound(c => c.FirstName).Title(Resources.FirstName);
                     colums.Bound(c => c.LastName).Title(Resources.LastName);
                     colums.Bound(c => c.MemberNumber).Title(Resources.MemberNumber);
                     colums.Bound(c => c.Active).Title(Resources.Active).HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<img src=\"Content/images/icons/<#=Active#>.png\" alt=\"<#=Active#>\" />");
                     colums.Bound(c => c.Id).Title(" ").HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.Member.ResetPassword()) + "/<#=Id#>\" title=\"" + Resources.ResetPassword + "\" >" + Resources.ResetPassword + "</a>");
                     colums.Bound(c => c.Id).Title(" ").HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.Member.Activate()) + "/<#=Id#>\" title=\"" + Resources.Activate + "\" >" + Resources.Activate + "</a>");
                     colums.Bound(c => c.Id).Title(" ").HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.Member.Deactivate()) + "/<#=Id#>\" title=\"" + Resources.Deactivate + "\" >" + Resources.Deactivate + "</a>");
                 })
                //.DataBinding(d => d.Ajax().Select("ListAjax", "Member", Model))
                .DataBinding(d => d.Ajax().Select(MVC.Member.ListAjax(Model).GetRouteValueDictionary()))
                .Sortable()
                .NoRecordsTemplate(Resources.NoData)
        %>
        <%= Html.AntiForgeryToken() %>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#btnSearch').click(function () {
                    var grid = $('#Grid').data('tGrid');
                    var searchModel = {
                        MemberNumber: $('#MemberNumber').val(),
                        Email: $('#Email').val(),
                        FirstName: $('#FirstName').val(),
                        LastName: $('#LastName').val(),
                        Phone: $('#Phone').val(),
                        Active: $('#Active').is(':checked')
                    };
                    grid.rebind(searchModel);
                    return false;
                });
            });
        </script>

        <%= Html.Telerik().ScriptRegistrar().jQuery(false).DefaultGroup(g => g.DefaultPath("~/Content/Javascript/2010.3.1110"))%>

And that's my controller

那是我的控制器

[GridAction]
    public virtual ActionResult ListAjax(SearchMemberModel search)
    {
        var gridModel = new GridModel<SerializableMember>();
        var data = _session.All<Member>();
        if (search != null)
        {
            if (search.Active) data = data.Where(x => x.Active);
            if (!string.IsNullOrEmpty(search.Email)) data = data.Where(x => x.Email.Contains(search.Email));
            if (!string.IsNullOrEmpty(search.FirstName)) data = data.Where(x => x.FirstName.Contains(search.FirstName));
            if (!string.IsNullOrEmpty(search.LastName)) data = data.Where(x => x.LastName.Contains(search.LastName));
            if (!string.IsNullOrEmpty(search.MemberNumber)) data = data.Where(x => x.MemberNumber.Contains(search.MemberNumber));
            if (!string.IsNullOrEmpty(search.Phone)) data = data.Where(x => x.Phone.Contains(search.Phone));
        }

        var list = new List<SerializableMember>(data.Count());
        list.AddRange(data.ToList().Select(obj => new SerializableMember(obj)));
        gridModel.Data = list;
        return View(gridModel);
    }

I can give you my search model class too :

我也可以给你我的搜索模型类:

public class SearchMemberModel
{
    [LocalizedDisplayName("MemberNumber")]
    public string MemberNumber { get; set; }

    [LocalizedDisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [LocalizedDisplayName("FirstName")]
    public string FirstName { get; set; }

    [LocalizedDisplayName("LastName")]
    public string LastName { get; set; }

    [LocalizedDisplayName("Phone")]
    public string Phone { get; set; }

    [LocalizedDisplayName("ActiveOnly")]
    public bool Active { get; set; }
}

Hope it can helps anyone out there!

希望它可以帮助任何人!

回答by Merritt

<script type="text/javascript">
    $(document).ready(function () {
        $('#apply').click(function () {
            var params = { 
                showDisabled : $('input[name=ShowDisabled]').attr('checked'), 
                showExpired : $('input[name=ShowDisabled]').attr('checked')
            };

            var grid = $('#Grid').data('tGrid');
            grid.rebind(params);
        });
    });
</script>

Here's the controller action bound to your select command:

这是绑定到您的选择命令的控制器操作:

[GridAction(EnableCustomBinding=true)]
public ActionResult _BindGrid(GridCommand command, string mode, int? id, bool showExpired, bool showDisabled)
{
    return View(new GridModel(GetMessageGridItems(command, mode, id,  showExpired, showDisabled)));
}

The param 'command' has the sorting and paging information. Note: this solution is for an ajax-ified grid. If you are doing straight-up posts, you can still use the GridCommand command parameter to maintain the state of paging/filtering/sorting.

参数 'command' 具有排序和分页信息。注意:此解决方案适用于 ajax 化的网格。如果您正在直接发布帖子,您仍然可以使用 GridCommand 命令参数来维护分页/过滤/排序的状态。

回答by Atanas Korchev

This is actually documented here.

这实际上记录在此处

回答by D?nu

Give this one a try: Telerik MVC Grid External Filter

试试这个:Telerik MVC Grid External Filter

It's a jquery plugin which enables you to set the filter by custom input controls.

它是一个 jquery 插件,可让您通过自定义输入控件设置过滤器。

回答by Eric Ziko

Here is a much easier way to pass parameters back from your form during the telerix ajax post back.

这是在 Telerix ajax 回发期间从表单传回参数的更简单的方法。

Simply hook into the global $.ajaxPrefilter event and use jquery to serialize the contents of your from to the URL that is being submitted. This will work with ASP.MVC model binding

只需挂钩全局 $.ajaxPrefilter 事件并使用 jquery 将 from 的内容序列化为正在提交的 URL。这将适用于 ASP.MVC 模型绑定

<script type="text/javascript">

$.ajaxPrefilter(function (options) {
    options.url = options.url + "&" + $("form").serialize();
});

</script>