简体   繁体   中英

Getting HTML Textbox value using Razor - MVC

I currently have table that displays a list of all of the issues. I added PagedList.MVC to the application as well as a jquery filterTable the issue is that when I click on a different page using the PagedListPager it loses all of the sort options at the top of the page. I believe I just need to add the parameters to the pagedlistpager but I am not sure how to get the value of the textbox. I was thinking about trying to use jquery and using the val() of the element but not sure if that is the best/easiest way to do this.

Here is my View:

@model  PagedList.IPagedList<ApIssues.Models.AP_Tasks>
@using System.Data.SqlClient
@using PagedList.Mvc;


@{
    ViewBag.Title = "Index";
}



<div class="search-sort-section">
    <h2>Search and Sort</h2>

    @using (Html.BeginForm("Index","ApIssues"))
    {
        <p>
            @Html.Label("Company: ")
            @Html.DropDownList("company", (SelectList)ViewBag.CompanyList, " ")

            @Html.Label("Warehouse: ")
            @Html.DropDownList("warehouse", (SelectList)ViewBag.WarehouseList, " ")

            @Html.Label("Past Due Only: ")
            @Html.DropDownList("pastDue", (SelectList)ViewBag.PastDueList, " ")

            @Html.Label("Assigned To/By: ")
            @Html.DropDownList("assignedToBy", (SelectList)ViewBag.UsersList, " ")

        </p>

        <p>
            @Html.Label("Open / Completed: ")
            @Html.DropDownList("openco", (SelectList)ViewBag.OpenCompList, " ")

            @Html.Label("Sort By: ")
            @Html.DropDownList("sortBy", (SelectList)ViewBag.SortByList, " ")

            @Html.Label("PO #: ")
            @Html.TextBox("poNumber")
            @Html.Label("Freight #: ")
            @Html.TextBox("freightNumber")
            @Html.Label("Vendor Name: ")
            @Html.TextBox("vendorName")
        </p>
        <p>
            @Html.Label("Issue Date")
            @Html.TextBox("beginIssueDate") - @Html.TextBox("endIssueDate")

            @Html.Label("Invoice Date")
            @Html.TextBox("beginInvoiceDate") - @Html.TextBox("endInvoiceDate")

            @Html.Label("Completed Date")
            @Html.TextBox("beginCompletedDate") - @Html.TextBox("endCompletedDate")
            @Html.Label("Quick Filter: ")
            @Html.TextBox("quickFilter")
        </p>
        <p>
            <input type="submit" value="Go" />
            <input type="button" value="Printable View" onclick=" location.href = '@Url.Action("PrintablePdf", "ApIssues")' " />
            <input type="button" value="Add New Task" onclick=" location.href = '@Url.Action("Create", "ApIssues")' " />
            <input type="button" value="Reporting" />
        </p>
    }


</div>



<div class="issue-table">
    <h2>A/P Issues</h2>
    <table id="data-table">
        <tr>
            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Task ID", "Index",
                    new { sortOrder = "TaskID", CurrentSort = ViewBag.CurrentSort })
            </th>
            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Task Date", "Index",
                    new { sortOrder = "TaskDate", CurrentSort = ViewBag.CurrentSort })
            </th>
            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Invoice Date", "Index",
                    new { sortOrder = "InvDate", CurrentSort = ViewBag.CurrentSort })
            </th>
            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Assigned To", "Index",
                    new { sortOrder = "AssignedTo", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("CC", "Index",
                    new { sortOrder = "CC", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("WHSE", "Index",
                    new { sortOrder = "Whse", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("PO #", "Index",
                    new { sortOrder = "PO", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Freight #", "Index",
                    new { sortOrder = "FreightNo", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Vendor Name", "Index",
                    new { sortOrder = "VendName", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Req. Completion Date", "Index",
                    new { sortOrder = "ReqCompDate", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th style="border: 2px solid black; text-align: center; width: 12%">
                @Html.ActionLink("Task Type", "Index",
                    new { sortOrder = "TaskType", CurrentSort = ViewBag.CurrentSort })
            </th>

            <th></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.ActionLink(item.TaskID.ToString(), "Task", new { id = item.TaskID })
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.TaskDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.InvDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.AssignedTo)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CC)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Whse)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.PO)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.FreightNo)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.VendName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ReqCompDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.TaskType)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.TaskID })
                </td>
            </tr>
        }

    </table>

    <br />
    <div id='Paging' style="text-align:center">
        Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
        of @Model.PageCount

        @Html.PagedListPager(Model, page => Url.Action("Index", new {page}))
    </div>
</div>
<head>
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="http://sunnywalker.github.io/jQuery.FilterTable/jquery.filtertable.min.js"></script>
    <script src="~/Scripts/Additional JS/jquery.tablesorter.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('table').filterTable(
            {
                minRows: 1,
                label: "Search :",
                inputSelector: "#quickFilter" ,
                placeholder: "Keyword"
            });
        });
    </script>
</head>

Here is my action:

public ActionResult Index(string sortOrder,string currentSort, int? page, string company, string warehouse,
            string pastDue, string assignedToBy, string openco, string sortBy, string poNumber, string freightNumber,
            string vendorName, string beginIssueDate, string endIssueDate, string beginInvoiceDate, string endInvoiceDate,
            string beginCompletedDate, string endCompletedDate)
        {
            //Variable Definitions
            const int pageSize = 20;
            var pageIndex = 1;
            pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
            IPagedList<AP_Tasks> tasks = null;

            // Instantiate the Entities
            var nxtDb = new nxtSQLEntities();
            var db = new Accounting_AaronTestEntities();
            var usersDb = new PDDAEntities1();

            //Query that gets the warehouses, companys, and users from the nxtDB and the PPP DB
            var whses = from w in nxtDb.icsds select w.whse;
            var coNames = from c in nxtDb.icsds select c.name;
            var userDb = new PDDAEntities1();
            var query1 = from u in userDb.Users where u.Cono == 1 select new { u.UserName, u.FirstName, u.LastName };
            var query2 = from gm in userDb.GroupMembers
                         join ug in userDb.UserGroups on gm.GroupID equals ug.GroupID
                         join u in userDb.Users on gm.UserName equals u.UserName
                         where ug.GroupName == "AP Department" || ug.GroupName == "MIS"
                         orderby new { u.LastName, u.FirstName }
                         select new { UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName };
            var query3 = query1.Concat(query2);

            var users = new List<string> { };
            users.AddRange(query3.Select(entry => entry.UserName));

            //Dropdown lists being created and using a viewbag to setup and communication line between the the conroller and view
            var warehouseList = new SelectList(whses);
            ViewBag.WarehouseList = warehouseList;
            var companyList = new SelectList(coNames);
            ViewBag.CompanyList = companyList;
            var pastDueList = new SelectList(new[]{"Yes", "No"});
            ViewBag.PastDueList = pastDueList;
            var usersList = new SelectList(users);
            ViewBag.UsersList = usersList;
            var openCompList = new SelectList(new[] { "Open", "Completed" });
            ViewBag.OpenCompList = openCompList;
            var sortByList = new SelectList(new[] { "Task ID", "Warehouse", "Assigned To", "PO Number", "Task Date" });
            ViewBag.SortByList = sortByList;



            tasks = GetFilteredSortedTasks(db,company, warehouse, pastDue, assignedToBy, openco, sortBy, poNumber,
                        freightNumber, vendorName, beginIssueDate, endIssueDate, beginInvoiceDate, endInvoiceDate,
                        beginCompletedDate, endCompletedDate).ToPagedList(pageIndex, pageSize);

            return View(tasks);

        }

Html.PagedListPager can take an additional parameter that is an expression that tells it how to generate the URL for the next page:

@Html.PagedListPager((IPagedList)ViewBag.OnePageOfItems, page => SomeMethodToGetUrlFor(page))

What you need to do basically is keep the current URL of the page (with all the appropriate querystring params for the filters and such) and add or update a page parameter. The "add or update" part makes this tricky, though: for example, you can't just tack on &page=N to the end of the URL as page may already be present in the querystring. I created a UrlHelper extension for just this purpose:

public static string ModifyQueryString(this UrlHelper helper, string url, NameValueCollection updates, IEnumerable<string> removes)
{
    NameValueCollection query;
    var request = helper.RequestContext.HttpContext.Request;

    if (string.IsNullOrWhiteSpace(url))
    {
        url = request.Url.AbsolutePath;
        query = HttpUtility.ParseQueryString(request.QueryString.ToString());
    }
    else
    {
        var urlParts = url.Split('?');
        url = urlParts[0];
        if (urlParts.Length > 1)
        {
            query = HttpUtility.ParseQueryString(urlParts[1]);
        }
        else
        {
            query = new NameValueCollection();
        }
    }

    updates = updates ?? new NameValueCollection();
    foreach (string key in updates.Keys)
    {
        query.Set(key, updates[key]);
    }

    removes = removes ?? new List<string>();
    foreach (string param in removes)
    {
        query.Remove(param);
    }

    if (query.HasKeys())
    {
        return string.Format("{0}?{1}", url, query.ToString());
    }
    else
    {
        return url;
    }
}

What this does is essentially let you pass in a NameValueCollection of parameters you want to add or update and/or a list of parameters you want to remove from the querystring. By default, it uses the current request URL, but if you pass in a URL it will do the transformation on that instead. Finally, it returns the modified URL back to the view.

I also added some additional methods to make working with this a little easier such as:

public static string UpdateQueryParam(this UrlHelper helper, string param, object value)
{
    return ModifyQueryString(helper, new NameValueCollection { { param, value.ToString() } }, null);
}

public static string UpdateQueryParam(this UrlHelper helper, string url, string param, object value)
{
    return ModifyQueryString(helper, url, new NameValueCollection { { param, value.ToString() } }, null);
}

So, if I just need to add/update one parameter, I don't need to actually instantiate a new NameValueCollection in my view.

Using these extensions, then, you can modify the URL appropriately with:

Url.UpdateQueryParam("page", page)

Which makes your pager line:

@Html.PagedListPager((IPagedList)ViewBag.OnePageOfItems, page => Url.UpdateQueryParam("page", page))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM