JqGrid and Search form - ASP.NET MVC

2019-03-04 02:19发布

问题:

Came across this article, link text, and reading through, the article had a screen shot of something that I want to provide on my site. This is what I want, alt text http://blogs.teamb.com/files/2009/04/jqgridsearchform_1250.png

Is jqGrid the best way to go? All I want is that search parameter interface. The search result I want to display in a tabbed window, which I will work on next.

回答1:

JqGrid will construct the search control shown in the image automatically. So if what is in the image is what you want, then yes, JqGrid is the way to go, since that's what I used to produce the screen shot you've included in the question.

Naturally, this control is based on the JqGrid, so you would need to use that. The search control isn't "standalone" (at least, not by design). The grid is quite configurable, though, so you may be able to get the look you want.

If you can't use the grid, then you probably can't use the filter/search control. But it's just HTML, so it's easy to copy.



回答2:

I'm assuming you want to search on your own form and controls and then display the results in jqGrid. Most of the solutions found online use jqGrid's own search controls, which might not be the prefered option for your problem.

I'll show a simple example on how to acomplish this:

1) Build your search form as needed:

@using (Html.BeginForm("Index", "Campaign", FormMethod.Post, new { id = "searchCampaigns" }))
{
    <table class="DetailsTable" cellpadding="2" cellspacing="1">
        <tr>
            <td>Title</td>
            <td>@Html.TextBoxFor(A => A.Titulo, new { Id = "search_title", })</td>
            <td>Created by</td>
            <td>@Html.DropDownListFor(A => A.CreatedByUserId, Model.UserList, new { Id = "search_createdBy" })
            </td>
        </tr>
        <tr>
            <td> </td>
            <td colspan="3"><button type="button" onclick="javascript:search();">
                    Search !</button>
            </td>
        </tr>
    </table>

2)

Implement your search function in order to read those search fields:

<script type="text/javascript">
    function search()
    {
        var searchValue_title = document.getElementById("search_title");
        var searchValue_createdBy = document.getElementById("search_createdBy");

        var extraQueryParameters = "";

        extraQueryParameters = "?title=" + searchValue_title.value;
        extraQueryParameters = extraQueryParameters + "&createdBy=" + searchValue_createdBy.value;

        jQuery("#SearchResults").jqGrid().setGridParam({url : '@Url.Action("GridData")' + extraQueryParameters}).trigger("reloadGrid")

    }
</script>

Please note that you actually don't need to use @HTML.TextBoxFor(...) to create the input elements. Unless you want make use of the dataAnnotation of MVC 3, you can make do with simple elements.

The search function just concatenates all the search parameters and appends them to GridData Action. The url should become something like http://mySite/Controller/GridData?title=hello&createdBy=3. This is then fed to the grid.

3) Implement an MVC controller function along these lines:

public JsonResult GridData(string sidx, string sord, int? page, int? rows, int? createdBy, string title)
{
    using (MyDataContext ddc = new MyDataContext())
    {
        var baseQuery = ddc.MyCampaign.AsQueryable(); 
        string gridCaption = "Search Results";

        if (!string.IsNullOrEmpty(titulo))
            baseQuery = baseQuery.Where(A => A.Title.Contains(title));

        if(createdBy.HasValue())
            baseQuery = baseQuery.Where(A=>A.idCreationUser = createdBy.Value);

        int pageIndex = Convert.ToInt32(page) - 1;
        int pageSize = rows.HasValue ? rows.Value : 10;
        int totalRecords = baseQuery.Count();
        int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

        var ds = (from A in baseQuery
                    select new
                    {
                        ID = A.ID,
                        Title = A.Title,
                    }).OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).ToList();

        var jsonData = new
        {
            total = totalPages,
            page = page,
            records = totalRecords,
            rows = from A in ds
                    select new
                    {
                        id = A.ID,
                        cell = new[] { A.ID.ToString(), A.Title }
                    },
            caption = gridCaption
        };


        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }
}

4) Please take note of the following issues:

The parameter names for the C# function must match the arguments that are passed on the query string build when you click the Search button. The .OrderBy(sidx + " " + sord) method requires that you use the Dynamic Linq DLL, available at: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx This has bugs, but for the most part, it works :)