Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104711

MVC: Dynamically populate html select

I have a field that is generated for each row in the view as follows:

@Html.DropDownListFor(m => m.MenuParentKey, ViewBag.MenuKeys as SelectList)      

But I want the drop-down to be populated for each row individually, by calling an action in the controller, here is what I mean:

public ActionResult GetMenuKeys(string currentMenuKey)
{
  var dictionary = MenuKeys.Where(mk => mk.Key != currentMenuKey);

  return View(new SelectList(dictionary,
      "Key",
      "Value",
      Page.DefaultParentKey));
}

currentMenuKey should be provided according to current row, I want the value of the current row to be excluded from the drop-down (notice it's the parent-key property).

Upvotes: 1

Views: 848

Answers (1)

Yan Brunet
Yan Brunet

Reputation: 4887

You could create a Helper that would return a SelectList instead.

That would allow you the call it directly from your view, you would also be able to pass the parameter as required.

I think that would be easier than calling an action on your controler.

From what I see here, the controler action does not fetch any other resources than the list.

You could go with something like this :

public static SelectList FilteredList( this HtmlHelper helper, MenuKeys keys, string CurrentMenuKey)
{
var dictionary = MenuKeys.Where(mk => mk.Key != currentMenuKey);

  return new SelectList(dictionary,
      "Key",
      "Value",
      Page.DefaultParentKey);
}

Then you could call it this way :

@Html.DropDownListFor(m => m.MenuParentKey, Html.FilteredList(ViewBag.MenuKeys as SelectList, m.currentKey))    

Upvotes: 1

Related Questions