简体   繁体   中英

Order List in MVC 4 ASP.NET i.e. Controller receiving 2 variables

I am trying to rewrite the default MVC Index controller that displays the list of records from a database. I am trying to have an order by function on 1 of the headings AND the ability to search on the page:

Controller code:

public ActionResult Index(String sortOrder, String searchString) {
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
        var profiles = from s in db.Profiles
                       select s;

        if (!String.IsNullOrEmpty(searchString))
        {
            profiles = profiles.Where(d => d.lastName.ToUpper().Contains(searchString.ToUpper()));
        }
        switch (sortOrder)
        {
            case "Name_desc":
                profiles = profiles.OrderByDescending(s => s.lastName);
                break;
            default:
                profiles = profiles.OrderBy(s => s.lastName);
                break;
        }
        return View(profiles.ToList());
    }

View Code:

<th>
    @Html.ActionLink("Last Name", "Index", new { sortOrder = "Name_desc" })
</th>

I have been trying various ways, but it seems as if I am not succeeding with the @html.actionLink calling the controller method

Followed this tutorial exact but not working: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

So to explain how I solved the answer...

The actionResult was a HttpPost back. So it would only accept input when a button is clicked. It seems as if @HTML.actionlinks only call the view methods.

I simply created a new Index(String sortOrder, String searchString) method and the view code was @Html.ActionLink("Last Name", "/Index", new { sortOrder = ViewBag.NameSortParm})

Its messy, but solved my issue nonetheless

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