aaarianme
aaarianme

Reputation: 282

Calling an action with parameter .Net Core

I have a MyMessages model that I put data into when the user logs in. it includes all the data needed. for every message that they have I do the following in view

                    for (int i = 0; i < Model.MyMessagesCount; i++)
                    {
                       <li class="list-group-item d-flex align-items-center mt-2">
                           <a>@Model.MessagesTitles[i]</a>
                           

                       </li> 

When the user clicks on each of the <a>, I want to show them that message in more details in a separate view where I pass MessageID to. How can I achieve that? How can I have all the <a> call the same action but with different MessageID as a parameter? (Something like this /User/Usermessages?MessageID=20)

Upvotes: 0

Views: 807

Answers (2)

Zhi Lv
Zhi Lv

Reputation: 21421

In the Index.cshtml page, you could directly set the a tag href attribute.

Code sample as below:

    public IActionResult Index()
    {
        List<MyMessages> messages = new List<MyMessages>()
        {
            new MyMessages(){ MessageId=1001, MessageTitile="AA"},
            new MyMessages(){MessageId =1002, MessageTitile="BB"},
            new MyMessages(){MessageId=1003, MessageTitile="CC"} 
        };
        return View(messages);
    }

    public IActionResult Details(int messageId)
    {
        return View();
    }

Index.cshtml page:

    @model List<SignalRChatSample.Models.MyMessages>

    <ul>
        @for (int i = 0; i < Model.Count(); i++)
        {
            <li class="list-group-item d-flex align-items-center mt-2">
                <a href="/Home/Details?messageId=@Model[i].MessageId.ToString()">@Model[i].MessageTitile</a> 
            </li>
        }
    </ul>

Then, the result like this (The url: Https://localhost:5001/Home/Details?messageId=1002):

enter image description here

Besides, as David said, you could also send the parameters via the route.

Upvotes: 1

David Liang
David Liang

Reputation: 21476

You can use anchor tag helper

<li>
    <a asp-controller="user" 
        asp-action="messages" 
        asp-area="" 
        asp-route-messageId="@Model.MessagesTitles[i].MessageId">
        @Model.MessagesTitles[i]
    </a>
</li>

asp-route-{parameter}: the parameter there is the name of the parameter you define in your action.

You can read more on https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-5.0

Upvotes: 2

Related Questions