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

1.4k views Asked by At

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

1

There are 1 answers

0
Gman16 On

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