asp.net-mvcviewparametershtml.actionlink

Is it possible to pass a parameter through @Html.ActionLink?


I need to use the same view, but have different data based on what button the user selects show up in the table. I would like to do this through just passing a parameter through the html.actionlink.

This is what i have currently in the View

 <li id="liOpenJobs">@Html.ActionLink("All Jobs", "AllJobs", "AdminJobs", new { filter = "All" })</li>

Controller

        [HttpGet]
    public ActionResult AllJobs(string filter)
    {
        if (PCSSession.Current.IsAuthenticated)
        {
            var jobs = new JobRepository();
            var model = new JobsHistoryViewModel();
            if(filter == "All")
            {
                model.jobHistory = jobs.GetAllJobs("alljobs");
            }


            return View(model);
        }

        return RedirectToAction("AdminLogin", "AdminLogin");

    }

Solution

  • Use this overload of the ActionLink helper method.

    public static MvcHtmlString ActionLink(
        this HtmlHelper htmlHelper,
        string linkText,
        string actionName,
        string controllerName,
        RouteValueDictionary routeValues,
        IDictionary<string, Object> htmlAttributes
    )
    

    The fourth parameter is the route values object and that will be used to generate the querystring items for the anchor tag's href attribute value. The fifth parameter is htmlAttributes. If you do not have any, simply pass null

    @Html.ActionLink("All Jobs", "AllJobs", "AdminJobs", new { filter = "All" }, null)
    @Html.ActionLink("Some Jobs", "AllJobs", "AdminJobs", new { filter = "some"}, null)
    

    This will generate HTML markup for anchor tags with href values like this

    /AdminJobs/AllJobs?filter=All and /AdminJobs/AllJobs?filter=some