Parth Ruparelia
Parth Ruparelia

Reputation: 265

How to pass multiple parameter from view to controller in .Net MVC

I need to pass 2 parameters id and date from view to controller side on the click event. It may be basic question but i am not able to do so.

I tried simply this code

Code <a href='/Abc/Details/id?=@website_id, date?=@date' class="" id="prev" >Prev</a>

and how to get those parameter at controller side.

I don't want to use "Ajax" or JavaScript if possible

Upvotes: 0

Views: 10944

Answers (3)

Jimmy Oku
Jimmy Oku

Reputation: 21

I found @Mighty Ferengi answer very useful. Thanks man!

public IActionResult Create(string FirstName, string MiddleName, string    
LastName, string ADUsername, string ADId, string ADName, string ADemail)
{
//do this
}

In Razor

<a asp-controller="Employees" asp-action="Create" asp-route-   
FirstName="@item.FirstName" asp-route-MiddleName="@item.MiddleName" asp- route-LastName="@item.LastName" 
asp-route ADUsername="@item.ADUsername" 
asp-route-ADId="@item.ADId" asp-route ADName="@item.ADName" 
asp-route- ADemail="@item.ADemail">Add Employee</a>

Upvotes: 1

Mighty Ferengi
Mighty Ferengi

Reputation: 836

I found it easier to declare your variables in the Controller Action:

public IActionResult Create(string FirstName, string MiddleName, string    
LastName, string ADUsername, string ADId, string ADName, string ADemail)
{
    //do this
}

Then you can assign the variables by name in the View:

<a asp-controller="Employees" asp-action="Create" asp-route-   
FirstName="@item.FirstName" asp-route-MiddleName="@item.MiddleName" asp-
route-LastName="@item.LastName" asp-route-ADUsername="@item.ADUsername" asp-
route-ADId="@item.ADId" asp-route-ADName="@item.ADName" asp-route-
ADemail="@item.ADemail">Add Employee</a>

Upvotes: 1

J-D
J-D

Reputation: 1575

First of all either you need to create custom route or enable MapMvcAttributeRoutes in your routeconfig file by adding below line of code.

routes.MapMvcAttributeRoutes();

Then in your controller above your defined action add something like below.

[Route("/Abc/Details/{id}/{date}")]

If you want to make it nullable then.

[Route("/Abc/Details/{id?}/{date?}")]

Your action method will be something like below.

[Route("/Abc/Details/{id?}/{date?}")]
public ActionResult Details(int id, string date)

Use @Html.ActionLink instead of hard coding your links.

If you wanted to go with custom route then add it above your default route.

routes.MapRoute(
                "MyCustomRoute",
                "Archive/{entrydate}",
                new { Controller = "ABC", action = "Details",Id  = UrlParameter.Optional,Date =  UrlParameter.Optional});

Now in your view

@Html.RouteLink("Link Text", "MyCustomRoute", new { Id = YourId, Date=YourDate})

Upvotes: 4

Related Questions