Home > Back-end >  How to pass a parameter to controller through view?
How to pass a parameter to controller through view?

Time:07-22

I am trying to pass an ICollection argument through a view to the TeamMemberController. I use SQL database with ASP.NET Core The database is stored locally. When clicking the red marked button there should appear a new page containing a list of the team members. The TeamMembers are currently displayed to the left of the marked button. The view button should send the parameter and direct us to the teamMemberpage But as you can see, the list appears to be empty

I have tried looking at the network in my browser and it gives me this:

Query String Parameters(1) :teamMembers: System.Collections.Generic.List`1[BugTracking.Data.Entities.TeamMember]

Video demonstrating issue https://youtu.be/dJbloxDCeok

Code:

Project Index View

@foreach (var item in Model) {
   <a asp-action="ShowTeamMembers" 
   asp-controller="TeamMember" 
   asp-route-teamMembers="@item.TeamMembers" >view</a>
 }

TeamMemberController

public class TeamMemberController : Controller
{
    private readonly DatabaseContext _context;

    public TeamMemberController(DatabaseContext context)
    {
        _context = context;
    }

    // GET: TeamMembers
    public async Task<IActionResult> Index()
    {
        return View(await _context.TeamMembers.ToListAsync());
    }

    public IActionResult ShowTeamMembers(ICollection<TeamMember> teamMembers)
    {
        return View(nameof(Index), teamMembers);
    }
 }

CodePudding user response:

The anchor tag will generate a url link to the given Controller/Action. Thus, it can only contain parameters that can be contained in the url of the link. So you cannot pass an object through on the url.

Try passing the Id of the team member

Project Index View

@foreach (var item in Model) {
   <a asp-action="ShowTeamMembers" 
   asp-controller="TeamMember" 
   asp-route-Id="@item.TeamMembers.ID" >view</a>
 }

TeamMemberController

public IActionResult ShowTeamMembers(int Id)
{
    var team = _context.TeamMembers.Where(team => team.ID == Id).FirstOrDefault()
    return View(nameof(Index), team);
}

CodePudding user response:

I solved the problem by sending the id of the project itself, instead of trying to send the List. I could then from the TeamMemberController handle that object and take bind the list to a variable.

Code:

Project Index View

<a asp-action="ShowTeamMembers" 
asp-controller="TeamMember" 
asp-route-Id="@item.Id" >view</a>

TeamMemberController

   public IActionResult ShowTeamMembers(Guid Id)
    {
        Project? project = _context.Projects.Include(p => p.TeamMembers).Where(p => p.Id == Id).FirstOrDefault();

        List<TeamMember> team = project?.TeamMembers ?? new();

        return View(nameof(Index), team);
    }
  • Related