Cavid
Cavid

Reputation: 133

Is it possible to use link inside DropDownList html helper?

I have a model class named categories that retrieves data from database :

public class HomeController : Controller
    {
        private StoreContext db;
        public HomeController()
        {
            db = new StoreContext();
        }
        public ActionResult Categories()
        {
         return View(db.Categories.ToList());
        }
   }

I want to use DropDownList helper method to display them in the view and I want all the categories inside it to be clickable, say, when you click them it has to adress you to the specified url belongs to the clicked category. Is there a way to make this happen with DropDownList helper? if yes then how?

Upvotes: 1

Views: 1336

Answers (1)

Fatikhan Gasimov
Fatikhan Gasimov

Reputation: 953

You can do this but you have to use Jquery . If you ask how?

For example:

My sample entity

  public class Category
     {
            public int Id { get; set; } 
            public string Url{ get; set; } 
            public string Name { get; set; } 
     }

My action:

  public IActionResult Categories()
    {
        var list = new List<Category>();
        for (int i = 0; i < 10; i++)
        {
             list.Add(new Category(){Id = i, Url = "https://stackoverflow.com", Name = "stackoverflow" });
        }

        var selectList = list.Select(x => new SelectListItem() {Value = Url, Text = x.Name})
            .ToList();
        return View(selectList);
    }

in my View:

 @Html.DropDownList("url",Model, "Choose a URL",  new { id = "url_list" })

and then using jquery you could subscribe for the change event of this dropdownlist and navigate to the corresponding url:

$(function() {
    $('#url_list').change(function() {
        var url = $(this).val();
        if (url != null && url != '') {
            window.location.href = url;
        }
    });
});

Upvotes: 1

Related Questions