0

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?

  • If you have select html in your redirected page, can't you just set option field to 'selected'? Something like this: ``? – Shukhrat Raimov Aug 17 '14 at 19:00
  • Or if I understand you correctly, you want to set ` – Shukhrat Raimov Aug 17 '14 at 19:12
  • @ShukhratRaimov Yes, I want the second option. Though I guess I need to provide a selected attribute in DropDownLink. –  Aug 17 '14 at 20:48

1 Answers1

0

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.

Shukhrat Raimov
  • 2,137
  • 4
  • 21
  • 27