dani_g
dani_g

Reputation: 21

Go to next record from Asp.Net MVC view

I've started working in asp.net MVC a few months ago. I'm using MVC4 with EF5.0 in C# at the moment.

-I haven't found a straight answer and working solution for this apparently simple situation...

Question: In controller action I want to be able to move to the next record based on the actual ID I'm seeing in the view. I'm trying to have a link or button in the view, to navigate to the next record. Please be aware it's not the next sequence number (as the ID you're seeing is 245 and the next record could have the ID 296).

I've tried this approach (similar from another post):

In Controller (Edit Method):

        `// Pk is the id that is passed into the Edit method
        var nextID = db.Customers.OrderBy(i => i.Pk)
                                 .SkipWhile(i => i.Pk != customer.Pk)
                                 .Skip(1)
                                 .Select(i => i.Pk);

        ViewBag.NextID = nextID;
        ...
        ...some other not relevant code...
        ...            
        return View(customer);`

But then, In View the ViewBag.NextID is receiving: System.Data.Objects.ObjectQuery`1 (instead of the next id 296).

Any help, suggestions, tips are welcome and appreciated.

Upvotes: 2

Views: 1917

Answers (3)

ataravati
ataravati

Reputation: 9155

Your LINQ query returns an IQuerable<Customer>. If you want to return a single Customer, you'll have to use either .First() or .Single() at the end of the query. But, you can also make your query simpler, like this:

var nextID = db.Customers.OrderBy(i => i.Pk).First(i => i.Pk > customer.Pk).Pk;

This will return the first Customer ID (Pk) greater than the given one.

Upvotes: 3

gcoleman0828
gcoleman0828

Reputation: 1542

I would also add that in an environment where the result might not return anything, it is often said that you should use FirstOrDefault as that will not bomb if no results exist and will return the default value for that type. First() on the other hand will throw an exception if no records are found.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239430

You haven't told it to return a single item. If you add something like .First() to the end of your LINQ query, you should be good.

Upvotes: 0

Related Questions