drop down list in mvc 3 - asp.net-mvc-3

Hey friends I am using drop down list in my mvc 3 project. Here the user choose one of the options and save it. And when he/she revisit the page than i have to make the initially saved value as selected value. Actually i am doing this with custom html helper as per need. But i am getting problem on it. I am doing this as:
else if (question_type == 7)
{
EAI.DAL.EaiEntities entities = new DAL.EaiEntities();
QuestionnaireRepository repository = new QuestionnaireRepository(entities);
SelectList typesList = repository.PopDdlList(qid);
output.Append(helper.Label(questiontext));
if (answer == "")
{
output.Append(helper.DropDownList("ddl" + question_id, typesList, "-- select type----));
}
else
{
output.Append(helper.DropDownList("ddl" + question_id, typesList, answer));
}
return helper.Raw(output.ToString());
}
Actually above code renders the selected value from database but it actually replacing the "-- select type ---" . So, After saving once if i visit the same page and save the page than i can get empty value in Formcollection.
So, please suggest the appropriate way of doing this

I usually add a few properties in my model:
int SelectedCategory { get; set; }
IEnumerable<SelectListItem> Categories { get; private set; }
and then load the data in my model constructor:
ProductService productService = new ProductService();
this.Categories =
productService.GetCategories()
.Select(c => new SelectListItem() { Text = c.Name, Id = c.Id.ToString() });
this.Categories.InsertAt(0, new SelectListItem() { Text = "--- Please Select ---", value = "" });
then in my Razor markup do something like:
#Html.DropDownListFor(m => m.SelectedCategory, Model.Categories)
This should auto wire up in the standard MVC way. Hope this helps.

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" })

MVC 3 dropdownfor populated but cannot get user's selection

I'm new to MVC 3. I want 3 dropdown lists. The user picks an item from each list and then retrieves the selections based on the matches. For my problem I'm just using 2 dropdowns and code snippets. I have all 3 dropdowns populated - the first two from Linq to Sql and the 3rd is an option list created with Razor (A-Z).
I'm missing the step of setting the values of what was chosen into MemberSetup.SelectedProgramID and MemberSetup.SelectedOrganizationID. I'd like the text stored in MemberSetup.SelectedProgramName and MemberSetup.SelectedOrganizationName respectively. I think if I can get the selected ids into the model, I can pass them through ActionLink and not deal with #Html.Hidden variables. However, no matter what is selection the model SelectedProgramID and SelectedOrganizationID are zero (expect 1, 2, 3 or 4 for Program ID and 1, 2, 5, or 6 for Organization ID).
Any help / corrections would be appreciated.
Model:
{
public int SelectedProgramID { get; set; }
public string SelectedProgramName {
get { return this._myProgramName; }
set { this._myProgramName = value; }
}
public IEnumerable<SelectListItem> ProgramList { get; set; }
public int SelectedOrganizationID { get; set; }
public string SelectedOrganizationName
{
get { return this._myOrganizationName; }
set { this._myOrganizationName = value; }
}
public IEnumerable<SelectListItem> OrganizationList { get; set; }
}
Controller:
{
var db = new STARDataContext();
MemberSetup setupModel = new MemberSetup();
setupModel.ProgramList = db.ProgramAlls.ToList()
.Select(p => new SelectListItem
{
Value = p.ProgramID.ToString(),
Text = p.ProgramName.ToString()
});
setupModel.OrganizationList = db.AreaAlls.ToList()
.Select(p => new SelectListItem
{
Value = p.AreaID.ToString(),
Text = p.AreaName.ToString()
});
return View(setupModel);
}
View:
{
#using ( Html.BeginForm() ) {
#Html.DropDownListFor(model => model.SelectedProgramID, Model.ProgramList)
#Html.DropDownListFor(model => model.SelectedOrganizationID, Model.OrganizationList, "Please select Organization", new { #class = "DropDownList" } )
#Html.Hidden("SelectedProgramID", Model.SelectedProgramID)
#Html.Hidden("SelectedProgramName", Model.SelectedProgramName)
#Html.Hidden("SelectedOrganizationID", Model.SelectedOrganizationID)
#Html.Hidden("SelectedOrganizationName", Model.SelectedOrganizationName)
#Html.ActionLink("Get Members", "Select", new {programID=Model.SelectedProgramID,orgID=Model.SelectedOrganizationID })
}
}
use hiddenFor instead of hidden,so your syntax should look like this
#Html.HiddenFor(a=>a.SelectedProgramName)
Since you have SelectedProgramID and SelectedOrganizationID defined, you won't need to use hidden field for it. To construct the dropdown, you should do something like this
Html.DropDownListFor(x=>x.ID,
new SelectList(Model.Products,"ID", "Sku", Model.ID), " select ")
For your reference: Use Html.DropDownListFor to get a selected value
The above class, controller and view are correct for presenting the drop-downs. This is why I was perplexed.
However, I had the SelectMember in the Get section. [HttpPost] and SelectMember can see what was selected.

How to populate the retrieved values from DB in ListBox using asp.net mvc

Can anyone help me how to populate the retrieved values in ListBoxFor. I tried this but doesn't works.
Code in Model:-
public List<SelectListItem> SafetyRepresentataives { get; set; }
public List<string> BusinessUnitSiteSafetyRepresentative { get; set; }
Code in Controller:=
var site = entityDB.ClientBusinessUnitSites.FirstOrDefault(m => m.ClientBusinessUnitSiteId ==
siteId);
var siteRepresentatives = from representatives in entityDB.ClientBusinessUnitSiteRepresentatives
where representatives.ClientBUSiteID == siteId
select representatives;
local.SafetyRepresentataives = (from o in entityDB.SystemUsersOrganizations.ToList()
from c in entityDB.Contact.ToList()
where o.OrganizationId == clientId && c.UserId ==
o.UserId
select new SelectListItem
{
Text = c.FirstName + "," + c.LastName,
Value = c.UserId.ToString()
}).ToList();
foreach (var representative in siteRepresentatives)
{
local.BusinessUnitSiteSafetyRepresentative.Add(representative.SafetyRepresentative.ToString());
}
Code in View:-
#Html.ListBoxFor(x => Model.BusinessUnitSiteSafetyRepresentative, new
MultiSelectList(Model.SafetyRepresentataives,"Value","Text"))
I have retrieved the values from DB as shown above. But I am unable to link these retrieved values to ListBox so as to populate them. How to do this?? Help me out please!!!!!!!!!
I think this link should help you
http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
In the sample they pass the combobox items in the viewbag.
I recomend you use a jquery plugin like autocomplete or typeahead from twitter bootstrap. So you can load asynchronously the elements.
Simply adding a default list helped me in resolving my issue. Here is the solution.
local.BusinessUnitSiteSafetyRepresentative = new List<string>();
foreach (var representative in siteRepresentatives)
{
local.BusinessUnitSiteSafetyRepresentative.Add(representative.SafetyRepresentative.ToString());
}

MVC3 DropDownListFor not populating selectedValue

I feel like I'm taking crazy pills. I have a dropdownlist for a view that reads from our database all of the wine producers we have. I want to set the selectedValue to a particular ID driven by the referring page. I can see it picks up the selectedValue in debug, I see the selected value populated (906 for this example), but it doesn't set the dropdownlist to the correct value when the page is rendered, it always defaults to 1 for the default value. I've tried creating the selectList in razor as opposed to my controller, but nothing works. Any help on this would be appreciated, I'm guessing it is something small.
Controller:
if (User.IsInRole("admin"))
{
if (ID != 0)
{
ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name", ID);
}
else
{
ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name");
}
}
View:
if (User.IsInRole("producereditor"))
{
<h3>#ViewBag.ProducerName</h3>
}
else
{
<div class="editor-label">
#Html.LabelFor(m => m.Wine.ProducerID, "Producer")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Wine.ProducerID, ViewBag.ProducerSelect as SelectList)
</div>
}
Tried the below but no success:
ViewBag.ProducerSelect = new SelectList(from p in db.Producers
orderby p.Name
select new { p.ProducerID, p.Name }
, "ProducerID", "Name", ID);
If you want to preselect an item, You set that value to your ProducerId property.
var yourViewModelObj=new YourViewModel;
yourViewModelObj.Wine.ProducerId=906; //or whatever value you want
return View(yourViewModelObj);
Suggestion : For better code readablity/Maintenance, Try to avoid ViewBag / ViewData and use a ViewModel to pass the data.
I would add a Property to my ViewModel to hold the Collection of Producers
public class WineViewModel
{
//Other Existing properties also
public IEnumerable<SelectListItem> Producers{ get; set; }
public string SelectedProducer { get; set; }
}
Then in yout GetAction method, you can set the value like this, If you want to set one select option as the default selected one.
public ActionResult CreateWine()
{
var vm=new WineViewModel();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.Producers= new[]
{
new SelectListItem { Value = "1", Text = "Prodcer A" },
new SelectListItem { Value = "2", Text = "Prodcer B" },
new SelectListItem { Value = "3", Text = "Prodcer C" }
};
//Now let's set the default one's value
vm.SelectedProducer = "2";
return View(vm);
}
And in your Strongly typed View,
#Html.DropDownListFor(x => x.SelectedProducer,
new SelectList(Model.Producers, "Value", "Text"), "Select Producer")
The HTML Markup generated by above code will have the HTML select with the option with value 2 as selected one.
I figured this out. I had ViewModel.wine.ProducerID elsewhere on the page in a hidden field, and that defaults to 1, so I just assigned that to passed in value, and it worked great. I knew it was something like that. Thanks!
User a ViewModel ex WineViewModel
public class WineViewModel
{
public Wine Wine { get; set; }
public SelectList PProducerList { get; set; }
public WineViewModel() { }
public WineViewModel(Wine wine)
{
this.Wine = wine;
}
}
Try the following in your controller
var model = new WineViewModel( selectwine);
model.ProjectTypeList = new SelectList( from p in db.Producers
orderby p.Name
select new { p.ID, p.Name }, "ID", "Name")
notice how I am exclusively declaring which is the ID and which is the Value in my SelectList
Then in your view do
#Html.DropDownListFor(model => model.Wine.ProducerID, Model.ProjectTypeList)

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