WebGrid DropDownList Selected Value? - c#

This might be a duplicate question but I couldn't find the solution anywhere.
Below is the working code when I use single model object for dropdownlist
#Html.DropDownListFor(model => model.LocationId, new SelectList(Model.LocationItems,
"Value", "Text",selectedValue: Model.LocationId))
The above code works & the selected value is based on the model object i.e. index for drop down is location id.
However, when I use web grid I'm unable to set the selected value for the dropdownlist like
grid.Column(
header: "Locations",
format: (item) => #Html.DropDownList("LocationId", Model.First().LocationItems.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
})))
The selected value in the drop down is always with index 1, where as it should be LocationId.
Is there any way to achieve this functionality?

You can add #Html.DropDownLists to grid in foreach like this:
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var col in Model)
{
columns.Add(
new WebGridColumn()
{
header: "Locations",
Format = (item) => #Html.DropDownList("LocationId", #col.LocationItems.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
}
)});
}
#grid.GetHtml(
columns: columns

Related

How to set default value for ASP.NET MVC DropDownList from ViewBag

In the controller Index I have the following:
ViewBag.Assignees = (await GetAllUsers()).Select(a =>
new SelectListItem
{
Text = a.DisplayName,
Value = a.Username,
Selected = a.DisplayName == "John Smith"
}).OrderBy(x => x.Text).ToList();
In the View, I have the following:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control"})
The dropdownlist populates as expected, however, the default (selected = true) value, which does exist, does not get set. Can someone advise what is wrong in the above?
UPDATE:
By Changing the SelectListItem.Value to a.DisplayName (same as SelectedListItem.Text) I achieved it. Still not sure what prevents the dropdownlist from displaying the item with Selected = true
If the model.Assignee comes with value, and if it is an int it will be defaulted to 0, it will override the SelectListItem selected value.
I suggest to set up the model.Assignee.
Here two ways that i use.
WAY 1
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Value", // property to be set as Value of dropdown item
"Text", // property to be used as text of dropdown item
"1"), // value that should be set selected of dropdown
new { id = "ddlAssignee", #class = "form-control"})
WAY 2
<select name="SelectName" value="1" class="w-100">
#foreach (var item in ViewBag.Collection) {
<option value="#item.Id">#item.Name</option>
}
</select>
I hope it work for you
#Html.DropDownListFor how to set default value
In your view set:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control", #value = "Default value"})
When you have list already defined.
Use This
#Html.DropDownList("CoverageDropDown", new SelectList(Model.youList, "Code", "Description",item.seletecItem), "Select")

How to bind an ID to the selected value of an #Html.DropDownList within a WebGrid

I have a View in my MVC project that has a WebGrid which is binded by an "Account" model that I passed into the View.
In my "Account" Controller I created a List of SelectedListItem's that I contains the DropDownList options which I then set to a ViewBag:
public ActionResult Index()
{
var accounts = db.Accounts;
var groups = db.Groups;
List<SelectListItem> groupList = new List<SelectListItem>();
foreach(var item in groups)
{
groupList.Add(new SelectListItem()
{
Value = item.group_id.ToString(),
Text = item.group_name
});
}
ViewBag.Groups = groupList;
return View(accounts);
}
The DropDownList contains 3 entries with their value and text as follows:
1, One
2, Two
3, Three
My problem is getting the group_id (Value) of the binded data to properly display the group_name (Text) on the DropDownList.
This is what I have so far:
grid.Column("group_id","Group", format: (item) => #Html.DropDownList("GroupId", (List<SelectListItem>)ViewBag.Groups))
The DropDownList does contains all 3 values I mentioned previously, it just doesn't set the DropDownList to the proper one at all for all the binded Accounts, as the image shows:
Account WebGrid
I have edited this post to add my View code.
#model IEnumerable<Account>
#{
ViewBag.Title = "Index";
WebGrid grid = new WebGrid(Model, rowsPerPage: 10);
}
<h2>Fee Invoices</h2>
#grid.GetHtml(tableStyle: "table table-bordered",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: grid.Columns(
grid.Column("account_name", "Account"),
grid.Column("account_number", "Account Number"),
grid.Column("as_of_date", "Date", format: (item) => string.Format("{0:MM/dd/yyyy}", item.as_of_date)),
grid.Column("approved", "Approved", format: #<text><input id="select" class="box" name="select" type="checkbox" #(item.approved ? "checked='checked'" : "") value="#item.approved" /></text>),
grid.Column("group_id","Group", format: (item) => #Html.DropDownList("GroupId", (List<SelectListItem>)ViewBag.Groups))
)
))
You can pass a Dictionary<int, string> of group_id and group_name to your view instead of the list of SelectListItem and then use it to create the DropDownList with the correct value selected.
In the controller
public ActionResult Index()
{
var accounts = db.Accounts;
var groups = db.Groups;
// this line creates a Dictionary<int, string> where group_id is the key and group_name the value
var groupsNames = groups.ToDictionary(x => x.group_id, x => x.group_name);
ViewBag.GroupsNames = groupsNames;
return View(accounts);
}
Then in the view declare a function like this (usually before the html part)
#functions
{
public List<SelectListItem> CreateSelectList(int groupId)
{
var newList = new List<SelectListItem>();
foreach (var val in (Dictionary<int, string>)ViewBag.GroupsNames)
{
newList.Add(new SelectListItem
{
Text = val.Value,
Value = val.Key.ToString(),
Selected = val.Key == groupId
});
}
return newList;
}
}
and use it to populate the drop down list
grid.Column("group_id", "Group", format: (item) => Html.DropDownList("GroupId", CreateSelectList((int)item.group_id)))
Or, if you don't need the drop down list but instead just want to display the name of the group you can do
grid.Column("group_id", "Group", format: (item) => ((Dictionary<int, string>)ViewBag.GroupsNames)[item.group_id])
and in this case you don't need the function.

How to get data to Dropdownlist from database in html view

I am creating an web page in which have a Dropdownlist. I have to retrieve data for the drop_down_list from the database. Is there any way to get data from the database to the html view my html code:
<select name="drop down"><option value="1">#test.list[i]</option></select>
I got the database value to the list variable but I don't know how to pass the data to the html view. Please help me in this issue.Thanks
You need to create Select List of Items :
Your Action with List of Items in View Bag :
public ActionResult ActionName()
{
List<SelectListItem> Items = new List<SelectListItem>();
CustReportName.Add(new SelectListItem() { Text = "List1", Value = "1", Selected = false });
CustReportName.Add(new SelectListItem() { Text = "List2", Value = "2", Selected = true });
ViewBag.ListItems = Items;
return View("ViewName");
}
For Multiple values from database table:
public ActionResult ActionName()
{
IEnumerable<SelectListItem> ItemsList = from item in YourTableObject
select new SelectListItem
{
Value = Convert.ToString(item.Id),
Text = item.ItemName
};
ViewBag.ListItems = new SelectList(ItemsList, "Value", "Text");
return View("ViewName");
}
Your DropdownList On view :
#Html.DropDownListFor(model => model.ItemId, new SelectList(ViewBag.ItemList, "Value", "Text", 0), "-Select Item-", new { #class = "form-control", #id = "ItemId" })
Cheers !!
It is just a simple two step process:
Step1 :Action method code
public ActionResult Index()
{
ViewBag.users = db.users.ToList();
}
Step2: cshtml code
#Html.DropDownListFor(model => model.someId, new SelectList(ViewBag.users, "userId", "userName"), "Select users")
Note: with this, you can bind n number of data from the database to dropdownlist
Hope it was useful
Thanks
Karthik

Having two values on SelectList() in asp.net

I'm trying to develop a website using asp.net mvc 4 & EF6 where I'm using dropdownlist to assign datas to my required textboxes. So far I've managed to assign data to two textboxes where one holds the value of the selected item of dropdownlist & one holds the text given for the selected item. But I need to add another value from the selected item. My codes are below,
Controller
ViewBag.Clients = new SelectList(db.ClientInfoes, "age", "fullname"); //This is given
ViewBag.Clients = new SelectList(db.ClientInfoes, "id", "age", "fullname"); //I want something like this
View
#Html.DropDownList("Clients", "Select...")
// Textboxes are populated automatically by using jQuery
#Html.TextBoxFor(a => a.Fullname, new { id = "clientName", #readonly = "readonly" })
#Html.TextBoxFor(a => a.Age, new { id = "clientAge", #readonly = "readonly" })
How can I assign more than one value in the SelectList? Any way I can do that would be fine. Need this help badly. Thanks.
It looks like you want to show name and age both in the dropdown text, in that case you need to project the result coming from database :
var ClientInfoes = db.ClientInfoes
.Select(x=>
new {
id = x.id,
name = x.fullname+","+x.age
});
ViewBag.Clients = new SelectList(ClientInfoes, "id", "name");

ListItem not highlighted even though selected is true

I am creating a list of months for a list box. The controller captures the selected months and stores them in session for if the user navigates away from the page then returns.
Here is the controller:
public ActionResult Index(int[] Months)
{
if (Session["Months"] == null || Months!= null)
Session["Months"] = Months;
else if (Months== null)
Months= Session["Months"] as int[];
IList<SelectListItem> MonthsList = utility.GetMonths().OrderBy(r => r.Name)
.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id.ToString(),
Selected = Months == null ? false : Months.Contains(r.Id)
}).ToList();
var model = new DataModel
{
SelectList = MonthsList,
Data = GetDataByMonths(Months)
};
return (model);
}
Here is the view:
#Html.ListBox("Months", Model.SelectList)
When the user selects items from the ListBox they are highlighted even after the form has been submitted. However when the user navigates away then returns the SelectListItems are correctly labeled as Selected = true but the DOM does not show this.
Any ideas on why this only doesnt work when session is used?
EDIT:
Tried:
#Html.ListBox("Months", new MultiSelectList(Model.Months, "Value", "Text", Model.SelectedMonths), new { size = 8 })
While debugging, the variables show the correct values, they are just not correctly highlighted in the DOM.
Did you try the SelectList type or MultiSelectList rather than an IEnumerable<SelectListItem>? I don't know of any other way to tell the ListBox which property is the value and which is the text.
i.e.
MultiSelectList list = new MultiSelectList(monthsList, "Value", "Text");
and return the list object?
I ended up creating the list box in html rather than using the #html.listbox()
<select name="Months" id="Months" multiple="multiple" size="8">
#foreach (var a in Model.Months)
{
<option value="#a.Value" #(a.Selected.ToString() == "True" ? "selected='selected'" : "")>#a.Text</option>
}
</select>

Categories

Resources