0

I have a index in controller and view following. When I enter student ID on textbox search, I want to display information of student and list all activities of them. How to do that. Thank you so much!

Controller:

public ActionResult Index(string Sid)
{
    var grad = db.Gradings.Include(g => g.Activity).Include(g => g.Student).Where(g => g.StudentID == Sid).ToList();      
}

View:

<div class="col-xs-4">
    <p>
        @using (Html.BeginForm())
        {
            <p>
                Student ID: @Html.TextBox("Sid",ViewBag.FilterValue as string)
                <input type="submit" value="Search" />
            </p>
        }
        <table class="table">
            <tr>
                <th>Activity Name</th>
                ....
            </tr>
            @foreach (var item in Model)
            {   
                <tr>
                    <td>@Html.DisplayFor(modelItem => item.Activity.Name)</td>
                    <td>@Html.DisplayFor(modelItem => item.Responsibility)</td>
                    ....
                </tr>
            }
        </table>
    </div>
    <h3> Total score: @ViewBag.Total</h3>

Thanks for your help!

  • You need to make the form a `FormMethod.Get` to post back to your `Index()` method, and then that method need to return the model to the view - `return View(grad);` –  Nov 29 '17 at 11:39
  • So what seems to be the problem? – CodingYoshi Nov 29 '17 at 11:52
  • when the code run, View display more student name record. How to display only one. I try to write the @Html.Displayfor(@model=>model.Student.Name) out of the foreach() statement, but it not work. – Tam Nguyen Nov 29 '17 at 12:05

1 Answers1

0

You need one action to serve your view initially when the user requests it:

public ActionResult Index()
{
    return View();     
}

Then you need another action to process the user's request when the request submits the form:

public ActionResult Index(string Sid)
{
    var grad = db.Gradings.Include(g => g.Activity).Include(g => g.Student).Where(g => g.StudentID == Sid).ToList();  

    return View(grad);    
}

Now grad is a List<Grading> and above we are passing it to the view as the model so make sure you use it in your view. You may need to include the namespace for List and Grading:

@model List<Grading>

Finally instead of using foreach in your view, use a for loop so your HTML tags have unique IDs. Right now (with foreach), all Grading records will have the same name and id attributes.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • Thanks for your answer. In the view in using @model PagedList.IPagedList Can you detail how to use the for loop? i wan to display: your name is: Student A table: Activity name Score instead table following: Student Name Activity name Score Student A abv 2 Student A xyz 2 – Tam Nguyen Nov 29 '17 at 12:40
  • See [this](https://stackoverflow.com/questions/3419711/how-can-i-use-html-displayfor-inside-of-an-iterator) if it helps. – CodingYoshi Nov 29 '17 at 14:06