如何根据 ASP.NET MVC 2.0 的列表框的选定值搜索 Telerik MVC 网格?

发布于 2024-10-31 08:07:34 字数 8045 浏览 0 评论 0原文

我有一个 Telerik MVC 网格,其中有一列 Names 、 Gender 、 Age 。我将使用绑定到性别的列表框(来自 SQL 2k8 表“Person”。我使用实体框架、POCO 类、存储库模式)。然后有一个图像按钮作为“搜索”。

当用户从列表框中选择几个值,然后单击“搜索”按钮时,应填充同一页面上的 Telerik MVC 网格(我正在渲染具有实际 Telerik MVC 网格的用户控件)。

怎么办?如何将选定的 ListBox 值传递回控制器操作“SearchPerson”。有一种方法可以使用 JQuery 来做到这一点。但我不知道该怎么做。请帮助我

编辑:代码

       <% using (Ajax.BeginForm("SearchVouDate", "ERA", new AjaxOptions { UpdateTargetId = "ProfileList", LoadingElementId = "LoadingImage", OnSuccess = "ShowMessage" }))
       { %>

    <div  class="SelectNPI" >
        <div class="DivSelectNPI">
            <input name="selection1" value="NPI" id="rdNPI" type="radio"  onclick="toggleLayer(this.checked);"  />
            <%:Html.Label(Resources.Strings.SelectNPI) %>
            <div id="ERANPI" style="display: none;"  >
               <%:Html.ListBoxFor(m => m.Eras.NPI, new MultiSelectList(Model.GetERAs, "NPI", "NPI", Model.NPIListBox), new { ID="NPIList", style = "width: 160px; height:50px" })%>
           </div>
        </div>
        <div class="SelectPIN">
            <input name="selection1" type="radio" id="rdPIN" value="PIN" onclick="toggleLayer1(this.checked);"  />
            <%:Html.Label(Resources.Strings.SelectPIN) %>
            <div id="ERAPIN" style="display: none;" >
               <%:Html.ListBoxFor(m => m.Eras.PIN, new MultiSelectList(Model.GetERAs, "PIN", "PIN", Model.PINListBox), new {ID="PINList", style = "width: 180px; height:50px" })%>
           </div>
        </div>
    </div>

            <input type="submit" class="btnSearchSubmit" id="PaySearchDateSubmit" name="PaySearchDateSubmit" value="Search" />
        </div>

    </div>
     <%} %>
     <br /><br />

     <div class="ERATopDiv" > <label id="Label1" class="lblSearchResult">  Search By Check Number</label> </div>
    <br />


    <div class="ERATopDiv"><label id="Label3" class="lblSearchResult" >Search Result</label> </div>
    <div id="ProfileList">
        <%Html.RenderPartial("SearchVoucherNum"); %>
    </div>
    <div id="results">
    </div>

</div>
<div id="EraPopupWindow">

</div>

我的控制器:

           [HttpPost]
         public ActionResult SearchVouDate(ERAViewModel era, FormCollection formValues)
         {
        try
        {

           if (formValues["Eras.NPI"] != null)
            {
              era.NPIListBox = formValues["Eras.NPI"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string[] selectedNPI = era.NPIListBox;
                ERAViewModel ervm = new ERAViewModel();
                foreach (string NPI in selectedNPI)
                {                        
                    ervm = this.WorkerService.SearchByNPI(formValues);
                    return PartialView("SearchVoucherNum", ervm);
                }


            }
            else
            {
                ERAViewModel eras = this.WorkerService.SearchByPIN(era.Eras.PIN);
                return PartialView("SearchVoucherNum", eras);
            }
        }
        catch (Exception ex)
        {
            bool reThrow = ExceptionPolicyWrapper.HandleException(ex, ExceptionPolicies.MVCPolicy);
            if (reThrow)
                throw;
        }
        return null;
    }

我在主视图上渲染的 PartialView (主视图包含我的 ListBox,partialView 包含我的 telerik MVC 网格)

     <% Html.Telerik().Grid(Model.GetERAs)
       .Name("ERA").TableHtmlAttributes(new { style = "height:20px" })
       .Scrollable(scroll => scroll.Enabled(true))
       .DataKeys(datakeys => datakeys.Add(m => m.EraId))
       .Columns(columns =>
           {
               columns.Bound(m => m.NPI).Title(Resources.Strings.NPI).Width(150)
                   .HtmlAttributes(new { style = "text-align:center" })
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" });
               columns.Bound(m => m.PIN).Title(Resources.Strings.PIN).Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.GroupName).Title(Resources.Strings.GroupName).Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.CheckNo).Title(Resources.Strings.CheckNo).Width(100)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.VoucherNo).Title(Resources.Strings.VoucherNo).Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.VoucherDate).Title(Resources.Strings.VoucherDate).Format("{0:dd/MM/yyyy}").Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.PaymentDate).Title(Resources.Strings.PaymentDate).Format("{0:dd/MM/yyyy}").Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.NonHippaVoucherPath).Title(Resources.Strings.NonHippaVoucherPath).Width(150).Format(Ajax.ActionLink("View Non Hippa voucher", "GetPdffile", "ERA", new { Id = "{0}" }, new AjaxOptions() { UpdateTargetId = "EraPopupWindow", HttpMethod = "Get" }, new { Style = "color:#FF0070;" }).ToString().Replace("{", "{{").Replace("}", "}}")).Encoded(false);
               columns.Bound(m => m.HippaVoucherPath).Title(Resources.Strings.HippaVoucherPath).Width(150).Format(Ajax.ActionLink("View Hippa voucher", "GetPdffile", "ERA", new { Id = "{0}" }, new AjaxOptions() { UpdateTargetId = "EraPopupWindow", HttpMethod = "Get" }, new { Style = "color:#FF0070;" }).ToString().Replace("{", "{{").Replace("}", "}}")).Encoded(false);  
               //columns.Bound(m => m.Non_hippa_voucher_path).HtmlAttributes("color:#8A2BE2").Format(Html.ActionLink("View Non Hippa voucher", "GetPdffile", "ERA", new { ID = "{0}" }, new { onclick = "return someFunction();", Style = "color:#8A2BE2" }).ToHtmlString()).Encoded(false).Title("").Width(150);
               //columns.Bound(m => m.Hippa_voucher_path).HtmlAttributes("color:#8A2BE2").Format(Html.ActionLink("View Hippa voucher", "GetFile/", new { ID = "{0}", Style = "color:#8A2BE2" }, "ERA/").ToHtmlString()).Encoded(false).Title("").Width(150);


           })

         //  .ClientEvents(clientEvents => clientEvents.OnDataBinding("dataBinding"))
           .DataBinding(databinding => databinding.Ajax().Select("AjaxERA", "ERA"))
           .EnableCustomBinding(true)
           .Pageable(paging =>{paging.Enabled(true) ;paging.PageSize(5) ;})
            .Sortable()
             .Filterable()
             .Footer(true)
            .Render();

%>

I have a Telerik MVC Grid where there is a column Names , Gender , Age . I am going to use a ListBox which is bound to Gender ( coming from SQL 2k8 Table" Person". I am using Entity Framework, POCO classes , Repository Pattern ). Then there is a Image button as " Search " .

When a user selects few values from ListBox and then hits the " Search" Button Telerik MVC Grid which is on the same page ( I am rendering a User control which has actual Telerik MVC Grid) should be populated .

how to do this ? how to pass the selected ListBox values back to controller Action " SearchPerson" . There is a way of doing this using JQuery . But i dont know how to do this . Please help me

EDIT : Code

       <% using (Ajax.BeginForm("SearchVouDate", "ERA", new AjaxOptions { UpdateTargetId = "ProfileList", LoadingElementId = "LoadingImage", OnSuccess = "ShowMessage" }))
       { %>

    <div  class="SelectNPI" >
        <div class="DivSelectNPI">
            <input name="selection1" value="NPI" id="rdNPI" type="radio"  onclick="toggleLayer(this.checked);"  />
            <%:Html.Label(Resources.Strings.SelectNPI) %>
            <div id="ERANPI" style="display: none;"  >
               <%:Html.ListBoxFor(m => m.Eras.NPI, new MultiSelectList(Model.GetERAs, "NPI", "NPI", Model.NPIListBox), new { ID="NPIList", style = "width: 160px; height:50px" })%>
           </div>
        </div>
        <div class="SelectPIN">
            <input name="selection1" type="radio" id="rdPIN" value="PIN" onclick="toggleLayer1(this.checked);"  />
            <%:Html.Label(Resources.Strings.SelectPIN) %>
            <div id="ERAPIN" style="display: none;" >
               <%:Html.ListBoxFor(m => m.Eras.PIN, new MultiSelectList(Model.GetERAs, "PIN", "PIN", Model.PINListBox), new {ID="PINList", style = "width: 180px; height:50px" })%>
           </div>
        </div>
    </div>

            <input type="submit" class="btnSearchSubmit" id="PaySearchDateSubmit" name="PaySearchDateSubmit" value="Search" />
        </div>

    </div>
     <%} %>
     <br /><br />

     <div class="ERATopDiv" > <label id="Label1" class="lblSearchResult">  Search By Check Number</label> </div>
    <br />


    <div class="ERATopDiv"><label id="Label3" class="lblSearchResult" >Search Result</label> </div>
    <div id="ProfileList">
        <%Html.RenderPartial("SearchVoucherNum"); %>
    </div>
    <div id="results">
    </div>

</div>
<div id="EraPopupWindow">

</div>

My Controller :

           [HttpPost]
         public ActionResult SearchVouDate(ERAViewModel era, FormCollection formValues)
         {
        try
        {

           if (formValues["Eras.NPI"] != null)
            {
              era.NPIListBox = formValues["Eras.NPI"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string[] selectedNPI = era.NPIListBox;
                ERAViewModel ervm = new ERAViewModel();
                foreach (string NPI in selectedNPI)
                {                        
                    ervm = this.WorkerService.SearchByNPI(formValues);
                    return PartialView("SearchVoucherNum", ervm);
                }


            }
            else
            {
                ERAViewModel eras = this.WorkerService.SearchByPIN(era.Eras.PIN);
                return PartialView("SearchVoucherNum", eras);
            }
        }
        catch (Exception ex)
        {
            bool reThrow = ExceptionPolicyWrapper.HandleException(ex, ExceptionPolicies.MVCPolicy);
            if (reThrow)
                throw;
        }
        return null;
    }

My PartialView which I am rendering on my main View ( Main View contains my ListBox and partialView contains my telerik MVC Grid )

     <% Html.Telerik().Grid(Model.GetERAs)
       .Name("ERA").TableHtmlAttributes(new { style = "height:20px" })
       .Scrollable(scroll => scroll.Enabled(true))
       .DataKeys(datakeys => datakeys.Add(m => m.EraId))
       .Columns(columns =>
           {
               columns.Bound(m => m.NPI).Title(Resources.Strings.NPI).Width(150)
                   .HtmlAttributes(new { style = "text-align:center" })
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" });
               columns.Bound(m => m.PIN).Title(Resources.Strings.PIN).Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.GroupName).Title(Resources.Strings.GroupName).Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.CheckNo).Title(Resources.Strings.CheckNo).Width(100)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.VoucherNo).Title(Resources.Strings.VoucherNo).Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.VoucherDate).Title(Resources.Strings.VoucherDate).Format("{0:dd/MM/yyyy}").Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.PaymentDate).Title(Resources.Strings.PaymentDate).Format("{0:dd/MM/yyyy}").Width(150)
                   .HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
                   .HtmlAttributes(new { style = "text-align:center" });
               columns.Bound(m => m.NonHippaVoucherPath).Title(Resources.Strings.NonHippaVoucherPath).Width(150).Format(Ajax.ActionLink("View Non Hippa voucher", "GetPdffile", "ERA", new { Id = "{0}" }, new AjaxOptions() { UpdateTargetId = "EraPopupWindow", HttpMethod = "Get" }, new { Style = "color:#FF0070;" }).ToString().Replace("{", "{{").Replace("}", "}}")).Encoded(false);
               columns.Bound(m => m.HippaVoucherPath).Title(Resources.Strings.HippaVoucherPath).Width(150).Format(Ajax.ActionLink("View Hippa voucher", "GetPdffile", "ERA", new { Id = "{0}" }, new AjaxOptions() { UpdateTargetId = "EraPopupWindow", HttpMethod = "Get" }, new { Style = "color:#FF0070;" }).ToString().Replace("{", "{{").Replace("}", "}}")).Encoded(false);  
               //columns.Bound(m => m.Non_hippa_voucher_path).HtmlAttributes("color:#8A2BE2").Format(Html.ActionLink("View Non Hippa voucher", "GetPdffile", "ERA", new { ID = "{0}" }, new { onclick = "return someFunction();", Style = "color:#8A2BE2" }).ToHtmlString()).Encoded(false).Title("").Width(150);
               //columns.Bound(m => m.Hippa_voucher_path).HtmlAttributes("color:#8A2BE2").Format(Html.ActionLink("View Hippa voucher", "GetFile/", new { ID = "{0}", Style = "color:#8A2BE2" }, "ERA/").ToHtmlString()).Encoded(false).Title("").Width(150);


           })

         //  .ClientEvents(clientEvents => clientEvents.OnDataBinding("dataBinding"))
           .DataBinding(databinding => databinding.Ajax().Select("AjaxERA", "ERA"))
           .EnableCustomBinding(true)
           .Pageable(paging =>{paging.Enabled(true) ;paging.PageSize(5) ;})
            .Sortable()
             .Filterable()
             .Footer(true)
            .Render();

%>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世界如花海般美丽 2024-11-07 08:07:34

最好的方法是使用 jQuery。

您需要 listBox 并在 AJAX 中绑定网格。

以下是我在应用程序中的一些示例代码:

查看

<div class="content-box-filter">
        <label>Filter:</label>
        <%= Html.DropDownList("Years", Model.Years) %>
    </div>
    <div class="content-box">
        <div class="content-box-header">
            <h3>News</h3></div>
        <div class="content-box-content">
            <%= Html.Telerik().Grid<News>()
                    .Name("Grid")
                    .Columns(colums =>
                     {
                         colums.Bound(c => c.Title).Title("Titre").ClientTemplate("<a href=\"" + Url.Action(MVC.News.Modifier()) + "/<#=IdValue#>\" ><#=Title#></a>");
                         colums.Bound(c => c.Title).Title("Inscriptions").ClientTemplate("<a href=\"" + Url.Action(MVC.News.Inscriptions()) + "/<#=IdValue#>\" >fichier excel</a>");
                         colums.Bound(c => c.Published).Title("Publiée").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<img src=\"../Content/images/icons/<#=Published#>.png\" alt=\"<#=Published#>\" />");
                         colums.Bound(c => c.CreationDate).Title("Date").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).Format("{0:MM/dd/yyyy}");
                         colums.Bound(c => c.IdValue).Title(" ").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.News.Modifier()) + "/<#=IdValue#>\" title=\"Modifier\" ><img src=\"../Content/images/icons/pencil.png\" alt=\"Modifier\" /></a>");
                         colums.Bound(c => c.IdValue).Title(" ").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).Format("<a id=\"deleteLink{0}\" href=\"#\" title=\"Supprimer\" onclick=\"if(confirm('Voulez-vous vraiment supprimer cette nouvelle?')){ return deleteNews('{0}');} else { return false;};\"><img src=\"../Content/images/icons/cross.png\" alt=\"Supprimer\" /></a>");
                     })
                    .DataBinding(d => d.Ajax().Select("ListAjax", "News", new { year = DateTime.Now.Year }))
                    .Sortable()
            %>
            <%= Html.AntiForgeryToken() %>
        </div>
    </div>
    <script type="text/javascript">
        var token = $('[name=__RequestVerificationToken]').val();
        $(document).ready(function() {
            $('#Years').val(<%=DateTime.Now.Year%>);
            $('#Years').change(function() {
                var grid = $('#Grid').data('tGrid');
                grid.rebind({ year: this.value });
            });
        });
        function deleteNews(newsId) {
            $.post('DeleteNews', { __RequestVerificationToken: token, id: newsId }, function(data) {
                if (data == 'true') {
                    $('#deleteLink' + newsId).parent().parent().remove();
                } 
                return false;
            });
            return false;
        };
    </script>

NewsController 操作:

[GridAction]
        public virtual ActionResult ListAjax(int year)
        {
            var gridModel = new GridModel<News>();
            gridModel.Data = _newsRepo.GetByYear(year);
            return View(gridModel);
        }

如果您仍有疑问,请告诉我。

The best way to do this is to use jQuery.

You need your listBox and to bind your grid in AJAX.

Here's some sample code I have in an application :

View

<div class="content-box-filter">
        <label>Filter:</label>
        <%= Html.DropDownList("Years", Model.Years) %>
    </div>
    <div class="content-box">
        <div class="content-box-header">
            <h3>News</h3></div>
        <div class="content-box-content">
            <%= Html.Telerik().Grid<News>()
                    .Name("Grid")
                    .Columns(colums =>
                     {
                         colums.Bound(c => c.Title).Title("Titre").ClientTemplate("<a href=\"" + Url.Action(MVC.News.Modifier()) + "/<#=IdValue#>\" ><#=Title#></a>");
                         colums.Bound(c => c.Title).Title("Inscriptions").ClientTemplate("<a href=\"" + Url.Action(MVC.News.Inscriptions()) + "/<#=IdValue#>\" >fichier excel</a>");
                         colums.Bound(c => c.Published).Title("Publiée").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<img src=\"../Content/images/icons/<#=Published#>.png\" alt=\"<#=Published#>\" />");
                         colums.Bound(c => c.CreationDate).Title("Date").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).Format("{0:MM/dd/yyyy}");
                         colums.Bound(c => c.IdValue).Title(" ").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.News.Modifier()) + "/<#=IdValue#>\" title=\"Modifier\" ><img src=\"../Content/images/icons/pencil.png\" alt=\"Modifier\" /></a>");
                         colums.Bound(c => c.IdValue).Title(" ").HeaderHtmlAttributes(new { @class = "center-text" }).HtmlAttributes(new { @class = "center-text" }).Format("<a id=\"deleteLink{0}\" href=\"#\" title=\"Supprimer\" onclick=\"if(confirm('Voulez-vous vraiment supprimer cette nouvelle?')){ return deleteNews('{0}');} else { return false;};\"><img src=\"../Content/images/icons/cross.png\" alt=\"Supprimer\" /></a>");
                     })
                    .DataBinding(d => d.Ajax().Select("ListAjax", "News", new { year = DateTime.Now.Year }))
                    .Sortable()
            %>
            <%= Html.AntiForgeryToken() %>
        </div>
    </div>
    <script type="text/javascript">
        var token = $('[name=__RequestVerificationToken]').val();
        $(document).ready(function() {
            $('#Years').val(<%=DateTime.Now.Year%>);
            $('#Years').change(function() {
                var grid = $('#Grid').data('tGrid');
                grid.rebind({ year: this.value });
            });
        });
        function deleteNews(newsId) {
            $.post('DeleteNews', { __RequestVerificationToken: token, id: newsId }, function(data) {
                if (data == 'true') {
                    $('#deleteLink' + newsId).parent().parent().remove();
                } 
                return false;
            });
            return false;
        };
    </script>

The NewsController action :

[GridAction]
        public virtual ActionResult ListAjax(int year)
        {
            var gridModel = new GridModel<News>();
            gridModel.Data = _newsRepo.GetByYear(year);
            return View(gridModel);
        }

Let me know if you still have question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文