Choosing selected item for dropdown list in action - c#

I have a page which allows users to change their privacy settings for:
Their posted recipes
Their profile
Their posted lists
I am trying to form my code so that when the users load this page, the dropdown lists which they use to select their privacy settings display their current setting, so if they had their recipe privacy set to "Registered users", whenever they load the privacy settings page I want it to start off with "Registered users" selected.
Initially I create a list of SelectListItem instances called PrivacySettings
List<SelectListItem> PrivacySettings = new List<SelectListItem>();
PrivacySettings.Add(
new SelectListItem
{
Text="Anybody",
Value = "0"
});
PrivacySettings.Add(
new SelectListItem
{
Text = "Registered users",
Value = "1"
});
PrivacySettings.Add(
new SelectListItem
{
Text = "Only me",
Value = "2"
});
Then I create three separate SelectList instances. Here is the part where I am assigning the selected value for each of the lists to the first value which matches the user's saved setting.
SelectList RecipePrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.RecipePrivacy.ToString()));
SelectList ProfilePrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUserProfile.Privacy.ToString()));
SelectList ListPrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()));
Then I assign each of these to separate ViewData keys
ViewData["RecipePrivacy"] = RecipePrivacyList;
ViewData["ProfilePrivacy"] = ProfilePrivacyList;
ViewData["ListPrivacy"] = ListPrivacyList;
In my view I retrieve these and store them into variables
var ProfilePrivacy = (SelectList)ViewBag.ProfilePrivacy;
var RecipePrivacy = (SelectList)ViewBag.RecipePrivacy;
var ListPrivacy = (SelectList)ViewBag.ListPrivacy;
And finally I use the Html.DropDownList() helper method to create the lists using the aforementioned variables
#Html.DropDownList("profile-privacy", ProfilePrivacy, new { #class = "profile-privacy" })
When the view is loaded, the first value ("Anyone" or value 0) is selected regardless of the user's actual setting.

you have to set the selected item of the SelectList like that:
SelectList ListPrivacyList = new SelectList(
PrivacySettings,
"Value",
"Text",
PrivacySettings.First(x => x.Value == LoggedInUser.ListPrivacy.ToString()).Value);

Related

preselect dropdown list razor page

I have the below code that I use to populate my dropdown in my Razor Page
I want to preselect a description - the "Value" of that needs to be set is found in
s.UserEstablishmentId
How can I preselect this on the dropdown
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
You're using linq to create a new SelectListItem for getEstablishments element. When creating each instance of a SelectListItem() you need to determine if Selected should be true or false. Simply replace YourConditionForSelectionHere with a method that returns a bool or syntax that returns a bool, shown below:
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Selected = (YourConditionForSelectionHere),
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
in the end something like this worked
Selected= (s.UserEstablishmentId==s.EstablishId)? true:false,

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

AutoMapper map Enum to SelectList - Selected value not working

I have created a map which convert an enum to a SelectList by using a custom implementation of ITypeConverter.
public class DeliveryModeToSelectListTypeConverter : ITypeConverter<ProductDeliveryMode, SelectList>
{
public SelectList Convert( ResolutionContext context ) {
ProductDeliveryMode pdm = (ProductDeliveryMode)context.SourceValue;
List<SelectListItem> items = new List<SelectListItem>();
SelectListItem sli1 = new SelectListItem() {
Text = StringEnum.GetStringValue( ProductDeliveryMode.DeliveryModeActivationByPin ),
Value = ( (int)ProductDeliveryMode.DeliveryModeActivationByPin ).ToString(),
Selected = (pdm == ProductDeliveryMode.DeliveryModeActivationByPin)
};
items.Add( sli1 );
[...other enum members here...]
SelectList sl = new SelectList( items, "Value", "Text", pdm );
return sl;
}
}
And then I have created a Map by using
Mapper.CreateMap<ProductDeliveryMode, SelectList>()
.ConvertUsing( new DeliveryModeToSelectListTypeConverter() );
Mapper.CreateMap<Product, ProductViewModel>()
.ForMember( p => p.DeliveryModeOptions, opt => opt.MapFrom( x => x.DeliveryMode ) )
[...other members here...]
.Include<ExperienceProduct, ExperienceProductViewModel>();
Mapper.CreateMap<ExperienceProduct, ExperienceProductViewModel>()
.IncludeBase<Product, ProductViewModel>()
));
Everything seems to works very nice except from the fact that the Selected value of the SelectListItem does not maintains its value. I have been able to step into the code and the SelectListItem sli1 it's correctly created with the selected value equal to true.
However when i check that value after a mapping the value is always false as you can see from the following screenshots.
Where do I am wrong with this code?
The problem is when you create the select list:
SelectList sl = new SelectList( items, "Value", "Text", pdm);
You're passing the selected item as pdm of type ProductDeliveryMode, which is being compared against the Value property of type string.
From your comment below, the solution was to pass pdm as a string.

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>

trying to set a dropdown in MVC

I almost have this solved but need a little push.
Here's what I have:
In the database I have a field called active that is a bit field (True/False)
I have placed a dropdownlist on the View form like this:
<%= Html.DropDownList("lstActive", new SelectList((IEnumerable)ViewData["ActiveList"])) %>
In my controller, I simply have this code to generate the True/False in the dropdown:
List<string> activeList = new List<string>();
activeList.Add("True");
activeList.Add("False");
ViewData["ActiveList"] = new SelectList(activeList);
I want to bind to the field in the database called active and select it in the dropdown. When I view it like this I get this:
alt text http://rjmueller.net/sitesimages/temp/dropdown.gif
So the questions are these:
Obviously I am not pointing to the Value and Text property but what is that in this case?
And how do I select the value that is in the database?
Any help would be appreciated.
First, this is probably better suited to radio buttons, not a select. Second, you really ought to have a view model with a property that is an IEnumerable<SelectListItem> that supplies the values for the select. You can construct that directly in the model.
var model = new ViewModel();
model.ActiveList = new List<SelectListItem>
{
new SelectListItem { Text = "Yes", Value = "true" },
new SelectListITem { Text = "No", Value = "false" }
};
model.Active = false; // this will be the default
return View( model );
Then in your view (strongly-typed to your view model type):
<%= Html.DropDownListFor( m => m.Active, Model.ActiveList ) %>
Using radio buttons, you can omit the list (since there are only the two choices).
<%= Html.RadioButtonFor( m => m.Active, true ) %> Yes
<%= Html.RadioButtonFor( m => m.Active, false ) %> No
Here's a couple of suggestions for you.
First, your DropdownList's name is "lstActive", so if you create a List<SelectListItem> called "lstActive" and pass that back in ViewData, you don't have to do anything fancy with boxing. Then your declaration looks like:
<%= Html.DropDownList("lstActive") %>
easy, huh?
In your controller, you create your List. Here's a method I've used:
private List<SelectListItem> GetAccounts(User user)
{
var items = new List<SelectListItem>();
foreach (Account account in user.Accounts)
{
var item = new SelectListItem();
item.Text = account.Name;
item.Value = account.AccountId.ToString();
if (ActiveAccount == account.AccountId)
item.Selected = true;
items.Add(item);
}
return items;
}
Basically, what I'm trying to point out is that you can set a property on your SelectListItem that you wish to be displayed as selected. Here, I'm using my own code for Users and Accounts, but you'd substitute your own data based on your db query.
First thing, you're recreating a SelectList the ViewData data, you should declare the DropBox as follows:
<%= Html.DropDownList("lstActive", ViewData["ActiveList"]) %>
Second, instead of creating a generic list on the controller, create a SelectList and add SelectListItems to it:
var activeList = new SelectList
{
new SelectListItem { Text = "True", Value = true },
new SelectListItem { Text = "False", Value = false }
};
ViewData["ActiveList"] = activeList;
This should clarify:
Drop-down Lists and ASP.NET MVC
For each select list element you need to set the Text and Value properties...
One solution could be as follows:
Model:
public class NameValue
{
public string Name { get; set; }
public string Value { get; set; }
}
Controller:
string currentActiveValue = myDB.active.ToString();
List<NameValue> yesNoList = new List<NameValue>
{
new NameValue { Name = "Yes", Value = "True" },
new NameValue { Name = "No", Value = "False" }
};
SelectList myActiveList = new SelectList(yesNoList, "Name", "Value", currentActiveValue);
ViewData["ActiveList"] = myActiveList;
View:
div>Is Active: <%= Html.DropDownList("ActiveList") %></div>

Categories

Resources