I would like to send back a parameter to a controller based on user selection in the view.
This is what I have in the view:
@model IEnumerable<Users>
@{
ViewBag.Title = "FieldSaver Users";
}
<h2>Users</h2>
@foreach(char c in ViewBag.Alphabet)
{
@Html.ActionLink(c.ToString(), "Home/" + c, new object { }, new { @class = "alphabet", @letter = c })
}
<div class="table-responsive">
<table class="table table-striped">
<tr>
<td>Username</td>
<td>First name</td>
<td>Last name</td>
</tr>
@foreach (var user in Model)
{
<tr>
<td>@user.UserName</td>
<td>@user.FirstName</td>
<td>@user.LastName</td>
</tr>
}
</table>
</div>
And this is the controller:
public ActionResult Home(string letter)
{
ViewBag.Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
using (var db = new App.Models.DbContext())
{
List<Users> users = (from p in db.Users
select p).ToList();
return View(users);
}
return View();
}
So, when someone will click on a letter in the alphabet links, I want to send back the value to the controller, currently the postback is happening but the letter parameter is null.
What am I doing wrong?
What you're currently using as new object { }
is where you provide the route data. You're adding it as an HTML attribute.
In your case, it should be like this:
@Html.ActionLink(c.ToString(),
"Home",
new { letter = c },
new { @class = "alphabet" })