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">


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)


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use anchor tag helper

    <a asp-controller="user" 

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

You can

Method 2

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>

        @for (int i = 0; i < Model.Count(); i++)
            <li class="list-group-item d-flex align-items-center mt-2">
                <a href="/Home/<a href="" class="__cf_email__" data-cfemail="0145647560686d723e6c64727260666448653c414c6e65646d">[email protected]</a>[i].MessageId.ToString()">@Model[i].MessageTitile</a> 

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

Calling an action with parameter .Net Core

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x