Hmtl.DropDownList using only ViewBag for selected value - asp.net-mvc

I can create a dropdown list with items from the ViewBag, but there doesn't seem to be a way to select the current item. I'm not using the model to achieve this, just want to use ViewBag, otherwise I'd have to create another model class just to wrap the select items and the actual data to display.
My code:
#Html.DropDownList("MyFilter", (IEnumerable<SelectListItem>)ViewBag.SelectItems, "Show All" )
There is no parameter to set the value of the select list. Am I overlooking something?
If I were to use DropDownListFor<> does this only work against the model?

You could try setting the MyFilter property in your ViewBag/ViewData:
public ActionResult Index()
{
ViewBag.SelectItems = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
// preselect the second item
ViewBag.MyFilter = "2";
return View();
}
But my recommendation is to use view models and the strongly typed version of the helper:
public ActionResult Index()
{
var model = new MyViewModel
{
SelectItems = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
},
// preselect the second item
MyFilter = "2"
};
return View(model);
}
and in your strongly typed view:
#model MyViewModel
...
#Html.DropDownListFor(x => x.MyFilter, Model.SelectItems, "Show all")

Related

How to create a static dropdown in Razor syntax?

After hours of looking on Google and Stack Overflow, I can not find one bloody example of how to build a totally brain dead simple dropdown list that does not come from a database. Honestly, I am having a hard time getting my head around MVC. Can someone please show me how to create this:
<select name="FooBarDropDown" id="FooBarDropDown">
<option value="Option1" selected>This is Option 1</option>
<option value="Option2">This is Option 2</option>
<option value="Option3">This is Option 3</option>
</select>
Using this:
#Html.DropDownList....
I am looking for an all-in-one-line solution... all in the view. I am having a devil of a time with the syntax.
I think this is what you are looking for. It would be best though to refactor list construction into view model or in controller.
#Html.DropDownList("FooBarDropDown", new List<SelectListItem>
{
new SelectListItem{ Text="Option 1", Value = "1" },
new SelectListItem{ Text="Option 2", Value = "2" },
new SelectListItem{ Text="Option 3", Value = "3" },
})
An an example of placing this in the controller might look like this:
public ActionResult ExampleView()
{
var list = new List<SelectListItem>
{
new SelectListItem{ Text="Option 1", Value = "1" },
new SelectListItem{ Text="Option 2", Value = "2" },
new SelectListItem{ Text="Option 3", Value = "3", Selected = true },
};
ViewData["foorBarList"] = list;
return View();
}
And then in your view:
#Html.DropDownList("fooBarDropDown", ViewData["list"] as List<SelectListItem>)
If this is truly a static list that you might have to reuse in other views / controllers, then I would consider putting this logic into a static class of sorts. Example:
public static class DropDownListUtility
{
public static IEnumerable<SelectListItem> GetFooBarDropDown(object selectedValue)
{
return new List<SelectListItem>
{
new SelectListItem{ Text="Option 1", Value = "1", Selected = "1" == selectedValue.ToString()},
new SelectListItem{ Text="Option 2", Value = "2", Selected = "2" == selectedValue.ToString()},
new SelectListItem{ Text="Option 3", Value = "3", Selected = "3" == selectedValue.ToString()},
};
}
Which then leaves you a few different ways of accessing the list.
Controller Example:
public ActionResult ExampleView()
{
var list = DropDownListUtility.GetFooBarDropDown("2"); //select second option by default;
ViewData["foorBarList"] = list;
return View();
}
View Example:
#Html.DropDownList("fooBarDropDown", DropDownListUtility.GetFooBarDropDown("2"))
Have a look at the docs for this overload
public static MvcHtmlString DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList
)
So just add a reference to your List<SelectListItem>() with your options.
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Option1", Value = "Option1"});
items.Add(new SelectListItem { Text = "Option2", Value = "Option2" });
items.Add(new SelectListItem { Text = "Option3", Value = "Option3", Selected = true });
You can even embed that in your view if you don't want to pass it from your controller.
#{
List<SelectListItem> items = ...
}
Then use it
#Html.DropDownList("FooBarDropDown", items)
You can initialize a SelectListItem list (done here directly in the view) and then pass it to the DropDownList helper:
#{
List<SelectListItem> Listitems = new List<SelectListItem>();
for(int i = 1; i <= 50; i++)
{
items.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
}
}
#Html.DropDownList("ddlSequence", Listitems , new { id = "ddlSequence", #class = "form-control" })

How to pass Kendo drop-down list selected value from Html.RenderAction to action method in the controller?

I need to pass the value of a Kendo drop-down list to the action method within a controller from a Html.RenderAction helper. I can't for the life of me recall how to do this. How do I pass the selected value to the controller? This would be the same method you would use for a normal drop-down list.
// Drop-down list
#(Html.Kendo().DropDownList()
.Name("dropDownList")
.DataTextField("Text")
.DataValueField("Value")
.OptionLabel("Please select")
.BindTo(new List<SelectListItem>
{
new SelectListItem
{
Text = "Test 1",
Value = "1"
},
new SelectListItem
{
Text = "Test 2",
Value = "2"
},
new SelectListItem
{
Text = "Test 3",
Value = "3"
}
}))
// RenderAction
#{Html.RenderAction("DoSomething", new { value = %dropDownListSelectedValue% }); }
// Controller
public ActionResult DoSomething(string value)
{
...
}

The selected item does not display when I use DropDownListFor

I am using the following to generate a drop down list:
#for (var index = 0; index < Model.AdminSummaries.Count(); index++)
{
<div class="rep_tr0">
<div class="rep_td0">
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status,
AdminStatusReference.GetAdminStatusOptions(),
new { id = string.Format("Status_{0}",index ) })
</div>
</div>
}
Here's the HTML it generates:
<select id="Status_1" name="AdminSummaries[1].Status"><option value="1">Released</option>
<option value="2">Review</option>
<option value="3">New</option>
</select>
Here's the class that gives the status options.
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "Released" },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
}
}
Everything works good EXCEPT it doesn't select the items correctly. There's no option with 'selected' to match the data in the AdminSummaries.
How can I make it so the correct select list items are selected?
Just to clarify this. My problem is that if there is a data record with a value of 3 for the status then when I look at the screen I see a select list with the word "Release" showing.
What I need is for the select list to show text that corresponds with the data value.
Here is the more accurate answer
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptionsFor(AdminSummaries arg)
{
var options = new[]
{
new SelectListItem { Value = "1", Text = "Released" },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
options.First(o=> o.Value == arg).Selected = true;
return options;
}
}
Set the SelectListItem.Selected property to true:
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "Released", Selected = true },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
}
}
It seams from the source code that the DropDownListFor method (actually the ViewDataEvaluator.Eval method) doesn't support expressions containing indexers. Because your expression: AdminSummaries[index].Status contains an indexer that's why the framework doesn't use the selected value from your model class.
The only solution is to specify the selected item when setting the SelectListItem collection, you can do this by passing the currently selected value to your GetAdminStatusOptions method:
View:
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status,
AdminStatusReference.GetAdminStatusOptions(Model.AdminSummaries[index].Status),
new { id = string.Format("Status_{0}",index ) })
A sample GetAdminStatusOptions implementation:
public static IEnumerable<SelectListItem> GetAdminStatusOptions(string selected = null)
{
var options = new[]
{
new SelectListItem {Value = "1", Text = "Released"},
new SelectListItem {Value = "2", Text = "Review"},
new SelectListItem {Value = "3", Text = "New"}
};
foreach (var option in options)
{
option.Selected = option.Value == selected;
}
return options;
}

Bind Html.DropDownList with static items

I have to bind an Html.DropDownList with just two items statically.
Text="Yes" Value="1"
Text="No" Value="0"
The important thing is that, I have to set the text and value fields.
How can I do this?
I used this is properly working
#Html.DropDownList("Status", new List<SelectListItem>
{
new SelectListItem{ Text="Active", Value = "1" },
new SelectListItem{ Text="Not-Active", Value = "0" }
})
It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.
Example:
var list = new SelectList(new []
{
new { ID = "1", Name = "name1" },
new { ID = "2", Name = "name2" },
new { ID = "3", Name = "name3" },
},
"ID", "Name", 1);
ViewData["list"]=list;
return View();
you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.
in the View:
<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>
Code below assumes you are using razor view engine if not you will need to convert it.
#{
var listItems = new List<ListItem>();
listItems.Add(new ListItem{Text="Yes", Value="1"});
listItems.Add(new ListItem{Text="No", Value="0"});
}
#Html.DropDownListFor(m=>m.SelectedValue, listItem);
You should consider creating the model in your code instead of the view. Also this would be a good candidate for an editor template.
if you want to be alittle explicity then try
#{
var domainsList = new SelectList(new []
{
new SelectListItem { Text = ".Com", Value = ".com", Selected = true },
new SelectListItem { Text = ".Shopping", Value = ".shopping"},
new SelectListItem { Text = ".Org", Value = ".org"},
new SelectListItem { Text = ".Net", Value = ".net"},
new SelectListItem { Text = ".AE", Value = ".ae"},
new SelectListItem { Text = ".Info", Value = ".info"},
}, "Value", "Text");
}
#Html.DropDownList("TopLevelDomains", domainsList)
This solved it for me:
<td>
#{ var RlistItems = new List<SelectListItem>();
RlistItems.Add(new SelectListItem { Text = "Select Room Type", Value = "0" });
RlistItems.Add(new SelectListItem { Text = "Meeting Room", Value = "1" });
RlistItems.Add(new SelectListItem { Text = "Office", Value = "2" });
RlistItems.Add(new SelectListItem { Text = "Cafeteria", Value = "3" });
}
#Html.DropDownListFor(model=>model.FirstOrDefault().RoomType
,RlistItems,RlistItems[item.RoomType.Value].Selected=true )
</td>
<select asp-for="CountryName" asp-items=#(new List<SelectListItem> { new SelectListItem {Text="India",Value="1" } ,new SelectListItem {Text="Japan",Value="2" }} ) class="form-control">
<option>SELECT COUNTRY -- </option>

Html Attribute for Html.Dropdown

I am using a dropdown list as follows.
<%=Html.DropDownList("ddl", ViewData["Available"] as SelectList,
new { CssClass = "input-config", onchange = "this.form.submit();" })%>
On its selection change I am invoking post action. After the post the same page is shown on which this drop down is present. I want to know about the HTML attribute for the drop down which will let me preserve the list selection change. But as of now the list shows its first element after the post.
e.g. The dropdoen contains elements like 1,2,3,etc. By default 1 is selected. If I select 2, the post is invoked and the same page is shown again but my selection 2 goes and 1 is selected again.
How can preserve the selection?
Thanks,
Kapil
You have to make the list of select list items again and tell which of the items is the selected one in every post (Selected property of the SelectListItem).
When you perform the post you will be setting the ViewData["Available"] again, you can set the select item here. So when you create the drop down list in the html the selected item is already selected. So your code could look something like:
ViewData["Available"] = new SelectList( items, "dataValueField", "dataTextField", "selectedValue" );
You have to take the property model ddl, or receive it as a parameter in the action, such as:
public ActionResult Action(Model model, string ddl)
Then to create ViewData [" Available "], you have to pass it as selected value
public ActionResult Action(Model model, string ddl)
{
ViewData["Available"] = List<SelectListItem>
{
new SelectListItem { Text = "1", Value = "1", Selected = (ddl == "1") },
new SelectListItem { Text = "2", Value = "2", Selected = (ddl == "2") },
new SelectListItem { Text = "3", Value = "3", Selected = (ddl == "3") }
};
return View(model);
}
OR:
public ActionResult Action(Model model, string ddl)
{
var list = List<SelectListItem>
{
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" }
};
ViewData["ddl"] = new SelectList(list, "value", "text", ddl);
return View(model);
}
EDIT: See also this
This worked for me:
<%=Html.DropDownList("Ibus", ViewData["Ibus"] as SelectList, new { **#class** = "dASDropDown" })%>

Resources