.Net 6 MVC EF6 IActionResult returned null

Caffero, Jordan 21 Reputation points
2022-05-05T04:33:56.503+00:00

I am working on a character sheet repository with a username and login. Currently the users are not setup but the Character table is a List within the User. The Character list displays properly based on the UserId but when I try to enter the character's detail page it returns null unless I hardcode the id.

View action to Detail:

@foreach(Character character in @Model.Characters)
{
    <div class="form-control">
        <a class="list-group-btn list-group-item-action d-flex gap-3 py-3" aria-current="true" asp-controller="FifthEd" asp-action="CharDetail">       
            <div class="d-flex gap-2 w-100 justify-content-between">
                <div>

Actions:
Controller : Repository

            public async Task<IActionResult> CharDetail(int id)
            {
                //id = 1;
                Character character = await _userRepository.GetCharacter(id);
                return View(character);
            }

Repository:

            public async Task<Character> GetCharacter(int id)
            {
                return await _context.Characters.FirstOrDefaultAsync(c => c.Id == id);
            }
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,148 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-05-06T07:00:56.667+00:00

    Hi anonymous user,

    Ok, I was able to add @azzedinehtmlsql .ActionLink("Character Detail", "CharDetail", new { id = @character.Id }) to get it to work but it breaks the original button.

    Is there something I can add to <a class="list-group-btn list-group-item-action d-flex gap-3 py-3" aria-current="true" asp-controller="FifthEd" asp-action="CharDetail"> to achieve the same result?

    You can use the asp-route-{value} attribute to add the parameter, like this (the controller name is "FifthEd" and action name is "CharDetail"):

     <a class="list-group-btn list-group-item-action d-flex gap-3 py-3" aria-current="true" asp-controller="FifthEd" asp-action="CharDetail" asp-route-id="@character.Id">Character Detail</a>  
    

    it is same with the following Html helper:

    @Html.ActionLink("Character Detail", "CharDetail", "FifthEd" , new { id = @character.Id })  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


0 additional answers

Sort by: Most helpful