Search code examples
asp.net-mvcactionlinkhtml.actionlink

How to set the value of a select field through htmlAttribute in MVC 5?


I have an ActionLink defined as in this:

@Html.ActionLink("Write a review", "Create", "Reviews")

The point is that, when it redirects to the Create view of the Reviews controller, there is a select field with the id of BusinessID. Therefore, I want to set the value of the select field to the specific entry when it opens the page. Let's say that the value that I want to set it is Picasso. How, can I achieve it? Is it possible to do it somehow using htmlAttributes?


Solution

  • You can accept id parameter of your selected item in your Create action method of ReviewsController, and then use object routeValues parameter of @Html.ActionLink() to send particular id you want to be set as selected. Something like this:

    @Html.ActionLink("Write a review", "Create", "Reviews", new {id = 1}, null); 
    

    then your Create action method should accept this id (e.g:

      public ActionResult Create(int id) 
      { 
          List<SelectListItem> items = new List<SelectListItem>(); //create <option> </option> items of DropDownList
          items.Add(new SelectListItem { Text = "da Vinci", Value = "0", Selected = (id == 0)});
          items.Add(new SelectListItem { Text = "Picasso", Value = "1", Selected = (id == 1)});
          items.Add(new SelectListItem { Text = "van Gogh", Value = "2", Selected = (id == 2)});
          ViewBag.Painters = items;
          return View();
       }
    

    which renders Create.chtml accordingly selected item:

    @Html.DropDownList("Painters")
    

    Note that DropDownList parameter("Painters") should have the same name as a ViewBag.Painters. As a result after clicking a link you will get selected item to Picasso, because it is Selected attribute will be true, as we have assigned it in Create action method.

    I think there could be smarter way to write this dropdownlist, but this action method works fine. I encourage you to read more about @Html.DropDownList helper method on the following links: www.asp.net and K.Scott Allen. Hope you can find this helpful.