Reputation: 55
Am new to mvc and I'm currently making a simple mvc 4 project. I kindly like to know how I can pass an argument from a view, to a method inside my Controller. Here is my code sample from the View:
@foreach (var item in Model)
{
<a href="@Url.Action("GetStudentsScore", "StudentsScore")">@item.idcourse</a>
}
Here is the method am calling from the control layer:
public ActionResult GetStudentsScore(string courseId)
{
List<StudentScore> resultToReturn = new List<StudentScore>();
List<StudentScore> resultFromTable = dataContext.StudentScores.ToList();
foreach (StudentScore item in resultFromTable)
{
if (item.courseid == courseId)
{
resultToReturn.Add(item);
}
}
return View(resultToReturn.ToList());
}
I want to be able to click the link and then call "GetStudentsScore" method in my control layer but I dont know how to pass the argument.
Upvotes: 2
Views: 1105
Reputation:
Change your link to
@foreach (var item in Model)
{
@Html.ActionLink(item.idcourse, "GetStudentsScore", "StudentsScore", new { courseId = item.idcourse})
}
Note this assumes that property idcourse
is typeof string
Side note: You can simplify your controller code to
public ActionResult GetStudentsScore(string courseId)
{
var model = dataContext.StudentScores.Where(x => x.courseid == courseId).ToList();
return View(model);
}
Upvotes: 3