Search code examples
c#asp.net-mvchtml.actionlink

Html.ActionLink Textbox Value


I need to put this value:

  @Html.DropDownList("region", new[]{ 
           new SelectListItem() { Text = "MA", Value = "MA" },
                new SelectListItem() { Text = "BC", Value = "BC" },
                     new SelectListItem() { Text = "ON", Value = "ON" },

          })

into here:

@Html.ActionLink("<<", "List", new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, zipCode = ViewData["zipCode"], searchType = ViewData["searchType"], distance = ViewData["distance"], region = ViewData["region"], country = ViewData["country"] })

ViewData["region"] is null and I cannot get the value, when I click the link. How do I put the DropDownList's region value into the query string? I set the region to a default of MA in my code:

public ViewResult List(string sortOrder, string currentFilter, string searchString, int? page, string zipCode, string region, int? distance, string searchType, string country)
    {
        _storeService = new StoreService();

         //sets defaults
         if (String.IsNullOrEmpty(zipCode))
         {
             zipCode = "02472";
         }

         if (String.IsNullOrEmpty(region))
         {
             region = "MA";
         }
    }

Solution

  • Since you can't set the URL on page load, I'd just add a click listener to the anchor tag, and update the link there:

    @Html.ActionLink("<<", "List", new { ... },
        new { onclick = "updateLink(this);" })
    

    The handler should retrieve the region from the regions drop-down, and update the link's href:

    function updateLink(anchor) {
        var select = document.getElementById('region');
        var region = select.options[select.selectedIndex].value;
        anchor.href = e.href + "&region=" + region;
    }