Dave
Dave

Reputation: 263

Display One record at a time in MVC through List

I have 5 records coming from a simple select stored procedure.

ID Name
1  RecordOne
2  RecordTwo
3  RecordThree
4  RecordFour
5. RecordFive

Requirement is to display one record at a time example:

Record One

Previous Next

Two Action links or buttons with Previous and Next text. If user clicks Next user will see

RecordTwo

and so on,same for previous case.

My model

namespace MVCLearning.Models

{

public class VMNews
{
    public List<Student> StudentDetails { get; set; }
}

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }

}
 }

Action

 public ActionResult Index()
    {
        VMNews objnews = new VMNews();
        objnews.StudentDetails = db.Database.SqlQuery<Student>("usp_studentdetails").ToList();
        return View(objnews);
    }

View

<div>
@foreach (var item in Model.SD.Take(1))
{
    <h3>@item.Name</h3>
    <h3>@item.Age</h3>

}
@Html.ActionLink("Next", "index", new { Model.SD[0].ID})
@Html.ActionLink("Previous", "index", new { Model.SD[0].ID })            

The way I have written the view is totally wrong am not getting how and what to write on the action and what to write on the View.

What will be one of the way to achieve this.

Upvotes: 1

Views: 2177

Answers (1)

user3559349
user3559349

Reputation:

Change you method to

public ActionResult Index(int? index)
{
  int max = 5; // modify based on the actual number of records

  int currentIndex = index.GetValueOrDefault();
  if (currentIndex == 0)
  {
    ViewBag.NextIndex = 1;
  }
  else if (currentIndex >= max)
  {
    currentIndex = max;
    ViewBag.PreviousIndex = currentIndex - 1;
  }
  else
  {
    ViewBag.PreviousIndex = currentIndex - 1;
    ViewBag.NextIndex = currentIndex + 1;
  }

  VMNews objnews = new VMNews();
  Student model = db.Database.SqlQuery<Student>("usp_studentdetails")
    .Skip(currentIndex).Take(1).FirstOrDefault();

  return View(model);
}

Note that the query has been modified to return only one Student since that is all that you require in the view. Also I have asssumed if a user enters a value greater than the number of records it will return the last record (you may in fact want to throw an error?)

The view now needs to be

@model Student

<h3>@Model.Name</h3>
<h3>@Model.Age</h3>

@if (ViewBag.PreviousIndex != null)
{
  @Html.ActionLink("Previous", "Index", new { index = ViewBag.PreviousIndex })
}
@if (ViewBag.NextIndex != null)
{
  @Html.ActionLink("Next", "Index", new { index = ViewBag.NextIndex })
}

Upvotes: 2

Related Questions