maintain state of dropdownlist in MVC3 - asp.net-mvc-3

How do I maintain the selected value of dropdownlist in MVC3?
I'm using the following code to create the drop down list:
<%= Html.DropDownList("PEDropDown",
(IEnumerable<SelectListItem>)ViewData["PEDropDown"],
new { onchange = "this.form.action='/Screener/Screener';this.form.submit();" }
)%>

Here is one example, I use. I am not sure, this is the way you use to populate the DropDownList
<%=Html.DropDownList("ddlCategories", IEnumerable<SelectListItem>)ViewData["PEDropDown"], "CategoryId", "CategoryName", Model.CategoryId), "Select Category", new { onchange = "this.form.action='/Screener/Screener';this.form.submit();"})%>
Another way is, make a select list in controller as follows
List<SelectListItem> CategoryList = new List<SelectListItem>();
foreach (var item in Categories)
{
CategoryList.Add(new SelectListItem
{
Selected = Model.CategoryId,
Text = item.CategoryName, Value = Convert.ToString(item.CategoryId) });
}
ViewData["PEDropDown"]=CategoryList;
and use in view as
<%:Html.DropDownList("ddlCategories",IEnumerable<SelectListItem>)ViewData["PEDropDown"], "CategoryId", "CategoryName", new { onchange = "this.form.action='/Screener/Screener';this.form.submit();"})%>

I'm not 100% sure I get what you want to do, but I assume you want to get the selected value from the dropdown list?
In that case:
new { onchange = "alert(this.options[this.selectedIndex].value);" }
I put it in an alert for now, because I don't know what you want to do with the value

pass the value back into your controller and then populate a List of SelectListItems in the controller:
public actionresult yourmethod (int idToPass)
{
List<SelectListItem> SLIList = new List<SelectListItem>();
foreach (Model model in dropdownList)
{
SelectListItem SLI = new SelectListItem();
SLI.text = model.CategoryName;
SLI.selected = model.CategoryId == idToPass;
SLIList.Add(SLI);
}
ViewData["myDDL"] = SLIList;
}

You may try this.
Using ViewBag instead of ViewData (I suggest, it is better to use Model object)
Html.DropDownList("PEDropDown", new SelectList(ViewBag.PEDropDown, "Key", "Value", Model.PEDropDownSelectedValue), new { onchange = "document.location.href = '/ControllerName/ActionMethod?selectedValue=' + this.options[this.selectedIndex].value;" }))
The fourth argument in SelectList is the selected value. It must be passed using the model object.
When you call the particular action method, set the model object as below.
public ActionResult ActionMethod(string selectedValue)
{
ViewModelPE objModel = new ViewModelPE();
// populate the dropdown, since you lost the list in Viewbag
ViewBag.PEDropDown = functionReturningListPEDropDown();
objModel.PEDropDownSelectedValue = selectedValue;
return View(objModel);
// You may use the model object to pass the list too instead of ViewBag (ViewData in your case)
}

Related

I can't fetch data from the db with a Html.DropDownListFor, in MVC 4 (or 5)

I have read some pages regarding DDls, but I can't get my DDLF (DropDownListFor) to work. I have a model, and a db, but I don't know how I can in the view show one DDLF.
What I get to work, is this code:
#foreach (var item in Model)
{
#Html.DropDownListFor(m => item.Id,
new SelectList(ViewBag.SjukhusDropDownList),
"Choose something")
}
But then I get several DDLs. And I don't know how to insert data into them, so the data to the user will get fetched from the db. Like sending an id with something to the action, to do something with it. But here, I can only click on anything in the list, but of course, nothing will happen since I haven't bound any data to any option in that select list.
Here's an example for DropDownListFor in MVC 4
In the model create two properties, one for the list itself and one for identifying the list entries. In this example the vu-number identifies a merchant:
public class MyModel
{
[Display(Name = "VU")]
public string vu{ get; set; }
public List<SelectListItem> merchantList{ get; set; }
}
Initialize and load model data in the Http GET method of the controller:
public ActionResult ShowMerchants()
{
MyModel model = new MyModel();
model.merchantList = GetMerchants();
model.vu = model.merchantList[0].Value;
return View(model);
}
Create the list items using some rows from database. I.e. you can use TableAdapter and DataTable to achieve it:
private List<SelectListItem> GetMerchants()
{
List<SelectListItem> merchantList = new List<SelectListItem>();
MyDataSet.viewVUDataTable myDataTable = new MyDataSet.viewVUDataTable();
MyDataTableAdapters.VUListTableAdapter myTableAdapter = new MyDataTableAdapters.VUListTableAdapter();
myTableAdapter.Fill(myDataTable);
// iterate over rows in datatable
for(int i=0; i< myDataTable.Rows.Count; i++)
{
// Text is shown in the dropdownlist
// Value is used to identify the selected item
merchantList.Add(
new SelectListItem { Text = myDataTable[i].text, Value = myDataTable[i].vu});
}
return merchantList;
}
and in the view:
#Html.DropDownListFor(
model => model.vu,
Model.merchantList,
new { #class = "form-control" })

how to select value by default in dropdown list when use viewdata["Country"] and get get list from database

i have country list stored in database and using viewdata to store all list now when i edit my task then i want to set my value in dropdown list. my code is
public ActionResult Edit(long EventId)
{
using (Event objEvent = new Event())
{
List<EventObject> lst = new List<EventObject>();
lst = objEvent.GetEventByEventId(EventId);
using (Country objContry = new Country())
{
ViewData["Country"] = new SelectList(objContry.GetAllCountry(), "Country", "Country");
}
return View(lst[0]);
}
}
at lst[0].Country is my a value which i want to selected by default in dropdownlist.
my view is
<h5>Country</h5>
#Html.DropDownListFor(model => model.Country, (SelectList)ViewData["Country"], new { id = "ddlCountry" })
You seem to be binding the dropdown to a complex property on your model (Country) which obviously is not supported. Dropdowns should be bound only to simple scalar type properties. So you should define a property that will hold the selected value on your EventObject view model:
public string SelectedCountry { get; set; }
Then in your controller action you should set this property to the value of the country you want to be preselected:
using (Country objContry = new Country())
{
ViewData["Countries"] = new SelectList(objContry.GetAllCountry(), "Country", "Country");
}
lst[0].SelectedCountry = "Argentina";
return View(lst[0]);
and in your view:
#Html.DropDownListFor(
model => model.SelectedCountry,
(SelectList)ViewData["Country"],
new { id = "ddlCountry" }
)
In case your Country property is a scalar type you could directly assign a value to it:
lst[0].Country = "Argentina";

Drop-down not working in ToSelectList extension method

I've got a nullable enum that, unlike others on the same page, doesn't work. I have an enum, Title whereby using the extension method will help to populate a drop-down list on the page. Here's what the ViewBag declaration looks like:
ViewBag.TitleList = EnumExtensions.ToSelectList<Title>("[select]");
Now, perhaps someone could explain it to me, but this is where the black magic happens when it comes to binding in MVC. If the page is invalid when calling if(ModelState.IsValid) then upon re-rendering the screen, the above statement is called again. However this time, the correct drop-down item will be selected (dependent on which one you had selected at the time).
Digging deeper, this is the method declarations:
public static SelectList ToSelectList<TEnum>(string nullEntry = null) where TEnum : struct
{
return ToSelectList<TEnum>(nullEntry, null);
}
public static SelectList ToSelectList<TEnum>(string nullEntry = null, string selectedValue = null) where TEnum : struct
{
var enumType = typeof(TEnum);
var values = Enum.GetValues(enumType).OfType<TEnum>();
List<SelectListItem> items = ToSelectList<TEnum>(values, nullEntry, selectedValue);
SelectList sl = new SelectList(items, "Value", "Text", selectedValue);
return sl;
}
public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, string nullEntry, string selectedValue = null)
{
List<SelectListItem> items;
if ((typeof(T).IsEnum))
{
items = enumerable.Select(f => new SelectListItem()
{
Text = f.GetDescription(),
Value = f.ToString(),
Selected = f.ToString() == selectedValue
}).ToList();
}
else
{
items = enumerable.Select(f => new SelectListItem()
{
Text = f.ToString(),
Value = f.ToString()
}).ToList();
}
if (!string.IsNullOrEmpty(nullEntry))
{
items.Insert(0, new SelectListItem() { Text = nullEntry, Value = "" });
}
return items;
}
There's just some overloads to handle random cases, although presumably some of these won't be needed.
As I say, the correct item will be selected for other enumerations, but for this particular one, Title, it will not. Here's the enum declaration:
public enum Title
{
Mr,
Miss,
Mrs,
Ms
}
And finally, the declaration using DropDownListFor on the page itself;
#Html.DropDownListFor(x => x.Title, (SelectList)ViewBag.TitleList)
The problem is that when I first visit the page, the selected item is always "[select]" (when the provided enum value is null in the model). However, the model property Title definitely has a value set, and the SelectedItem property is set for the drop-down list too, but on screen, it defaults to "[select]" which is unexpected.
Any ideas?
Could it be because of the name Title? Try changing it to another name just to see.
Maybe you should try adding String.Empty so it the drop down list will default to a blank
#Html.DropDownListFor(x => x.Title, (SelectList)ViewBag.TitleList, String.Empty)

MVC SelectList Drop down default

In the SelectList drop down, I like if the Count is 1, I like to default the value of what is there in the drugfamilylist which in this case is just 1 value. I cannot figure out how to do this.
I had the following below:
var drugfamilylist = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
if (drugfamilylist.Count == 1)
{
ViewBag.DrugFamily = new SelectList(drugfamilylist);
}
I tried but that idd not work either :
var drugfamilylist = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
if (drugfamilylist.Count == 1)
{
ViewBag.DrugFamily = new SelectList(drugfamilylist,drugfamilylist);
}
Typically I would have View strongly-typed to a ViewModel. The ViewModel would contain both the list of available items and the corresponding value of the currently selected element.
public class MyViewModel
{
public IList<string> DrugFamilyList;
public string SelectedDrugFamily;
}
In the controller you could then populate both the list of available items and the Selected items when the list of available items was a single element.
public ActionResult MyAction()
{
var vm = new MyViewModel();
vm.DrugFamilyList = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
vm.SelectedDrugFamily = (vm.DrugFamilyList.Count==1) ?
vm.DrugFamilyList[0] : null;
return View(vm);
}
And then use the HtmlHelper to build the select box:
#Html.DropDownListFor(m => m.SelectedDrugFamily, new SelectList(Model.DrugFamilyList, Model.SelectedDrugFamily))
However, if you didn't want to use the recommended ViewModel pattern, you could always accomplish the same thing with ViewBag.
ViewBag.DrugFamilyList = (from dt in DataContext.Drugs
select dt.Drugvalue).Distinct().ToList();
ViewBag.SelectedDrugFamily = (ViewBag.DrugFamilyList.Count==1) ?
ViewBag.DrugFamilyList[0] : null;
And then in the View use a similar helper:
#Html.DropDownList("desiredfieldname", new SelectList(ViewBag.DrugFamilyList, "", "", ViewBag.SelectedDrugFamily ))
This was written free-hand and not tested. I hope it helps.

How do you properly create a MultiSelect <select> using the DropdownList helper?

(sorry, there are several item here but none seems to allow me to get this working.)
I want to create a DropDownList which allows multiple selection. I am able to populate the list but I can't get the currently selected values to seem to work.
I have the following in my controller:
ViewBag.PropertyGroups = from g in db.eFinGroups
where g.GroupType.Contents == "P"
select new
{
Key = g.Key,
Value = g.Description,
Selected = true
};
ViewBag.SelectedPropertyGroups = from g in company.Entities
.First().Properties.First().PropertyGroups
select new {
g.eFinGroup.Key,
Value = g.eFinGroup.Description };
In the view I have:
#Html.DropDownListFor(model => model.PropertyGroupsX,
new MultiSelectList(ViewBag.PropertyGroups
, "Key", "Value"
, ViewBag.SelectedPropertyGroups),
new { #class = "chzn-select", data_placeholder = "Choose a Property Group", multiple = "multiple", style = "width:350px;" })
PropertyGroupX is a string[] in the model.
I have tried all types of iterations with the selected properties... passing just the value, just the key, both, etc.
Also, what type is PropertyGroupX supposed to be? Is string array correct? Or should it be a dictionary that contains the current propertygroups? I really am having a hard time finding doc on this.
Someone suggested I should be using ListBoxFor. I have changed to that and still have the same issue. The selected values are not being set as selected when the option tags are rendered. Here is what I have tried:
#Html.ListBoxFor(model => model.PropertyGroups, new MultiSelectList(ViewBag.PropertyGroups, "Key", "Value"))
I have tried the model.PropertyGroups as a collection of string matching the Values, as a collection of Guid matching this IDs and as an anonymous type with both a Key and Value to match the items in the ViewBag. Nothing seems to work.
You don't use DropDownListFor if you want to create a multiselect list. You use the ListBoxFor helper.
View model:
public class MyViewModel
{
public string[] SelectedIds { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new MyViewModel
{
// preselect the first and the third item given their ids
SelectedIds = new[] { "1", "3" },
// fetch the items from some data source
Items = Enumerable.Range(1, 5).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
})
};
return View(model);
}
View:
#model MyViewModel
#Html.ListBoxFor(x => x.SelectedIds, Model.Items)

Resources