2

我在局部视图中定义了一个 webgrid。(这是一个 MVC 4 项目。) webgrid 不是局部视图中唯一的东西,因此 webgrid 绑定到局部视图模型中的一个列表。

当单击列标题时,网格会按应有的方式填充和排序,但是当我通过调用操作方法(通过使用 Ajax.BeginForm 设置的表单帖子)重新填充网格,然后单击列标题时,网格内容消失。(action 方法使用用户在表单上提供的搜索条件查询数据库。)

这可能是什么原因造成的?如何解决?

部分视图开始于:

@model DonationImport.Models.GiftWithSplits

部分视图的内容在由以下指定的形式内:

@using (Ajax.BeginForm("SearchConstit", "Batch", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "constitSearchArea" }))

WebGrid 定义如下:

@{
    var constitGrid = new WebGrid(source: Model.SearchResults, rowsPerPage: 100, ajaxUpdateContainerId: "constitGrid");                       
    <div style="overflow-x: scroll; width: 100%;">
        <div style="width: 1910px;">
            @constitGrid.GetHtml(htmlAttributes: new { id = "constitGrid" },
                columns: constitGrid.Columns(
                    constitGrid.Column(format: @<text><button onclick="selectConstituent('@item.Constituent_ID')" >select</button></text>, style: "searchResultsColumnWidth"), 
                    constitGrid.Column("Constituent_ID", header: "ConstitID", style: "searchResultsColumnWidth", format: @<text>@Html.ActionLink((string)item.Constituent_ID, "PriorGifts", new { constitID = item.Constituent_ID }, new { target = "Prior Payments" })</text>),
                        constitGrid.Column("IsActive", header: "Active", style: "searchResultsColumnWidth"),
                        constitGrid.Column("LastName", header: "Last", style: "searchResultsColumnWidth"),
                        constitGrid.Column("FirstName", header: "First", style: "searchResultsColumnWidth"),
                        constitGrid.Column("MiddleInitial", header: "M.I.", style: "searchResultsNarrowColumnWidth"),
                        constitGrid.Column("Spouse", header: "Spouse", style: "searchResultsColumnWidth"),
                        constitGrid.Column("EmailAddress", header: "E-mail", style: "searchResultsWideColumnWidth"),
                        constitGrid.Column("AddressLine1", header: "Address Line 1", style: "searchResultsWideColumnWidth"),
                        constitGrid.Column("City", header: "City", style: "searchResultsWideColumnWidth"),
                        constitGrid.Column("State", header: "State", style: "searchResultsColumnWidth"),
                        constitGrid.Column("Zip", header: "Zip", style: "searchResultsWideColumnWidth"),
                        constitGrid.Column("SearchResultsText", header: "Search Results", style: "searchResultsWideColumnWidth"),
                        constitGrid.Column("IsActivePledge", header: "Pledge", style: "searchResultsNarrowColumnWidth"),
                        constitGrid.Column("ReceiptWarning", header: "Receipt Warning", style: "searchResultsWideColumnWidth"),
                        constitGrid.Column("IsMember", header: "Mbr", style: "searchResultsNarrowColumnWidth")),
                        alternatingRowStyle: "altrow")
        </div>
    </div>
}

单击时:

<input type="submit" value="Search" /> 

在表单中,调用的action方法如下:

[HttpPost]
public PartialViewResult SearchConstit(DonationImport.Models.GiftWithSplits g)
{           
    GiftWithSplits giftWithSplits = new GiftWithSplits(); // model (object) to be returned to the partial view

    // send back gift data which we are currently using
    giftWithSplits.GiftToVerify = g.GiftToVerify;

    // search using provided data
    string middleInitial = empty2null(g.GiftToVerify.SourceMiddleName);
    if (!string.IsNullOrWhiteSpace(middleInitial))
        middleInitial = middleInitial.Substring(0, 1); // just supply the initial, not the entire name

    string zip = empty2null(g.GiftToVerify.SourceZip);
    if (!String.IsNullOrWhiteSpace(zip))
        zip = zip.Substring(0, 5); // we want only the first 5 digits of the zip

    giftWithSplits.SearchResults = db.SearchDonor(null, g.GiftToVerify.DonationSourceCode, empty2null(g.SourceAcctMemo), null, empty2null(g.GiftToVerify.SourceLastName), 
        empty2null(g.GiftToVerify.SourceFirstName), middleInitial, empty2null(g.GiftToVerify.SourceAddress1),
        empty2null(g.GiftToVerify.SourceCity), empty2null(g.GiftToVerify.SourceState), zip, empty2null(g.GiftToVerify.SourceCountry),
        empty2null(g.GiftToVerify.SourceEmailAddress), empty2null(g.GiftToVerify.SourcePhone)).ToList();
    if (giftWithSplits.SearchResults.Count == 0)
    {
        SearchDonor_Result emptyResult = new SearchDonor_Result();
        emptyResult.Constituent_ID = "[None Found]";
        giftWithSplits.SearchResults.Add(emptyResult);
    }

    return PartialView("_ConstitSearch", giftWithSplits);
}

您可能会说,我是这种 MVC 方法的初学者。

其他想法(稍后添加)...

问题的根源似乎是 WebGrid HTML 帮助为列标题生成的链接是基于与生成网格的操作方法相关的 URL。首次显示网格时,链接为:/Batch/Verify/34?sort=FirstName&sortdir=ASC,因为网格是作为整个验证视图的一部分构建的(来自验证操作方法)。但是,当搜索手动输入的搜索条件时,网格是从仅填充部分视图的 SearchConstit 操作方法构建的,因此列标题链接中的 URL 现在是:/Batch/SearchConstit?sort=FirstName&sortdir=ASC。

此外,“搜索”按钮与 POST 相关联,因为它需要从表单字段传递数据以用作搜索条件;然而,WebGrid 列标题使用的是 GET,显然没有办法强制它们发布。因此,问题似乎归结为如何在不发布表单的情况下从表单字段传递搜索条件。

我可以想到一个使用 Session 变量的可能解决方案,但我很犹豫这样做。

另一种选择可能是放弃使用 WebGrid。

有任何想法吗?

4

2 回答 2

0

当我在寻找相同问题的解决方案时,我发现了你的问题。我也面临同样的问题。我使用网络网格来显示数据。我使用了过滤器/分页。我也使用文本框在网格中进行搜索。我正在打电话进行搜索。当我单击过滤器和分页按钮时,Webgrid 消失了。我google了很多,没有找到任何解决方案。最后我找到了解决方案,所以想到了发布。您需要使用 get ajax 调用而不是 post 调用来解决您的问题。不要使用 beginform post 进行搜索。

Index.cshtml is my main view. Here i m rendering partial view (_GridPartialView.cshtml). Index view has one webgrid and search text box.
I am using ajax call to search in webgrid. Ajax code is mention below.

**Index.cshtml:**

@model List<Login>
@{
    ViewBag.Title = "User";
}


<h2 style="background-color: grey">User</h2>

<table>

    <tr>
        <td>
           <input type="text" id="txtSearch" placeholder="  Search..." onkeyup="Search()" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            @Html.ActionLink("Create New User", "CreateUser")</td>
    </tr>
    <tr>
        <td>

                <div id="divPartialView">
                    @Html.Partial("~/Views/Shared/_GridPartialView.cshtml", Model)
                </div>

        </td>
    </tr>
</table>


<script type="text/javascript">


    function Search() {
        var searchVal = $("#txtSearch").val();

        $.ajax({

            type: "GET",
            url: '/User/Search',
            data: { searchString: searchVal },
            dataType: 'html',
            success: function (data) {
                $('#divPartialView').html(data);

            }

        });

    }
</script>

_GridUserPArtialView.cshtml: This is partial view used in index view.

@model List<Login>
  <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <style type="text/css">
        .webGrid { margin: 4px; border-collapse: collapse; width: 500px;  background-color:#FCFCFC;}
        .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
        .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
        .alt { background-color: #E4E9F5; color: #000; }
        .gridHead a:hover {text-decoration:underline;}
        .description { width:auto}
        .select{background-color: #389DF5}
    </style>

         @{
             var grid = new WebGrid(null, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "grid");
        grid.Pager(WebGridPagerModes.NextPrevious);
        grid.Bind(Model, autoSortAndPage: true, rowCount: Model.Count);}
       <div id="grid">
        @grid.GetHtml(

        tableStyle: "webGrid", mode: WebGridPagerModes.All,

                firstText: "<< First",
                previousText: "< Prev",
                nextText: "Next >",
                lastText: "Last >>",
                headerStyle: "header",
                alternatingRowStyle: "alt",
                selectedRowStyle: "select",
                columns: grid.Columns(

                grid.Column("UserName", "User Name", style: "description"),
                grid.Column("FirstName", "First Name"),
                grid.Column("LastName", "Last Name"),
                grid.Column("Action", format: @<text>

         @if (@item.LoginUserName != "administrator"){
                  @Html.ActionLink("Edit", "Edit", new { id=item.LoginUserName}) 
                  @Html.ActionLink("Delete","Delete", new { id = item.LoginUserId},new { onclick = "return confirm('Are you sure you wish to delete this user?');" }) 

                 }
                            </text>,  style: "color:Gray;" , canSort: false)
         )) 

</div>

**UserController.cs**: This is Search action method inside. usercontroller. It is HTTPGET.

[HttpGet]
        public PartialViewResult Search(string searchString)
        {
            List<Login> userListCollection = new List<Login_User>();

            userListCollection = Login_User_Data.GetAllUsers();

            if (Request.IsAjaxRequest())
            {

                if (!string.IsNullOrEmpty(searchString))
                {
                    Log.Info("UserController: Index() Started");
                    var searchedlist = (from list in userListCollection
                                        where list.FirstName.IndexOf(searchString,StringComparison.OrdinalIgnoreCase) >=0
                                        || list.LoginUserName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0
                                        || list.LastName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0
                                        select list
                                            ).ToList();

                    return PartialView("~/Views/Shared/_GridPartialView.cshtml", searchedlist);

                }
                else
                {
                    Log.Info("UserController: Search(Login_User user) Ended");
                    return PartialView("_GridPartialView", userListCollection);
                }
            }
            else
            {
                return PartialView("_GridPartialView", userListCollection);
            }

            Log.Info("UserController: Search() Ended");
        }



Hope this will help you. Let me know if you have any concern.
From: www.Dotnetmagics.com
于 2016-07-29T06:41:21.033 回答
0

解决方案非常简单,您需要执行 GET,每当您对 web 网格进行排序或分页时,它会尝试获取数据并点击 HttpGet Action,其工作原理如下:

    [HttpGet]
    public ActionResult YourActionMethod()
    {
        return PartialView("YourView",YourModel);
    }

最好的部分是,在排序时,请求也会发送一个名为“sortBy”的参数,您可以在此处使用它并决定要对绑定的模型与网格做什么。您可以使用浏览器中的“开发人员工具”检查排序标头将命中的 URL。

注意:默认情况下,它将触发的操作方法与控制器名称相同。

于 2017-02-01T20:12:44.720 回答