I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a #Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.
The code looks as follows
The create method
public ActionResult Create()
{
var parents = db.Organizations.OrderBy(o => o.Title).ToList();
var organization = new Organization();
return View(organization);
}
Extract from the Razor template
<div class="editor-field">
#Html.DropDownList("ParentGuid",
new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
"ParentGuid", "Title", Model.ParentGuid))
</div>
So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.
I am not much familiarize with # however, if you tried the overload?
#Html.DropDownList("ParentGuid",
new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
"ParentGuid", "Title", Model.ParentGuid), "Your empty option text here")
You could add a row with an empty string to your model before passing it to the view, no?
You could recreate the array previous to adding it to the list. Something like this:
List<SelectListItem> itms = new List<SelectListItem>();
var blank = new SelectListItem();
blank.Selected = true;
itms.Add(blank);
foreach (var stat in model)
{
var s = new SelectListItem();
s.Text = stat.Text;
s.Value = stat.FeedBackTypeID + "";
itms.Add(s);
}
and then use that
In your controller Create(), just add an empty string to the head of the "parents" list.
I ended up using
<div class="editor-field">
#Html.DropDownListFor(model => model.ParentGuid,
new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
"OrganizationGuid", "Title", Model.ParentGuid), "")
</div>
The method serving the template looks like this
public ActionResult Create()
{
try
{
ViewBag.Organizations = db.Organizations.OrderBy(o => o.Title).ToList();
var organization = new Organization();
return View(organization);
}
catch (Exception e)
{
ViewData["error"] = string.Concat(e.Message, " ", e.StackTrace);
return RedirectToAction("Index");
}
}
Related
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
Wrapping my head around MVC.
I have a list of items. I need to load the screen with some of these selected by default.
Loading the items is one thing, trying to select some by default isn't working for me.
Any idea where I am going wrong?
I know there are many answers to a similar question, though I can't seem to translate the answers to my needs.
Here is the code I have, and tried - i am also trying to understand the various options in the html helpers. Please take this into consideration when posting a solution.
This is the most recent iteration of my code; i have gone through a bunch....
In my Controller:
public ActionResult Index()
{
ViewBag.Statuses = AddStatuses();
return View();
}
private MultiSelectList AddStatuses()
{
string[] defaultSelected = { "Ready", "Done", "Error" };
List<SelectListItem> listItems = new List<SelectListItem>();
List<Status> s = allTypes.GetStatuses();
s.ForEach(status =>
{
listItems.Add(new SelectListItem()
{
Text = status.Name,
Value = status.ID.ToString(),
Selected = true,// defaultSelected.Contains(status.Name)
});
});
return new MultiSelectList(listItems, "Value", "Text");
}
In an attempt to test my defaultSelected.Contains, i just commented it out to select ALL as true... still didn't work...
I have tried these in my view
#Html.DropDownList("Statuses", null, null, new { #class = "form-control", multiple = true, id="queueStatuses" })
#Html.ListBox("Name", ViewBag.Statuses as MultiSelectList, new { #class = "form-control", id = "queueStatuses" })
#Html.ListBox("Statuses", null, new { #class = "form-control", id = "queueStatuses" })
I a) don't understand what i am doing and b) can't get it to work... :)
I am looking for:
You can use the ListBoxFor helper method along with the user of a view model to pass the items for your list box.
So create a new view model to transfer data from your action method to view
public class CreateIssue
{
public List<SelectListItem> Statuses { set;get;}
public int[] SelectedStatuses { set;get;}
}
Now in your GET action, create an object of this, load the Statuses collection and send it to the view. If you want to preselect some items, set the SelectedStatuses property.
public ActionResult Index()
{
var vm = new CreateIssue();
//Hard coded for demo. You may replace with values coming from db table.
vm.Statuses = new List<SelectListItem> {
new SelectListItem { Value="1", Text="Ready"},
new SelectListItem { Value="2", Text="Done"},
new SelectListItem { Value="3", Text="Building"},
new SelectListItem { Value="4", Text="Error"},
};
//For preselecting items, set it here
vm.SelectedStates=new int[] { 2,3};
return View(vm);
}
and your in your view, which is strongly typed to the view model, use the ListBoxFor helper method.
#model CreateIssue
#using (Html.BeginForm())
{
<label>Select many statuses</label>
#Html.ListBoxFor(m => m.SelectedStatuses, Model.Statuses)
<input type="submit"/>
}
Thank you #Shyju. I am sure your answer works.
As mentioned in my comments though, I don't want to go through the hoops of having a view model in this instance. I was looking for a simple way to implement this.
Seems all i needed to do was change my MultiSelectList and pass in an array of selected 'value's.
This fixes my issue:
private MultiSelectList AddStatuses()
{
string[] defaultSelected = { "3", "5", "6" };
List<SelectListItem> allItems = new List<SelectListItem>();
List<Status> s = allTypes.GetStatuses();
s.ForEach(status =>
{
allItems.Add(new SelectListItem()
{
Text = status.Name,
Value = status.ID.ToString(),
});
});
return new MultiSelectList(allItems, "Value", "Text", defaultSelected);
}
And my ListBox is the same. Went with this one in the end:
#Html.ListBox("status", (IEnumerable<SelectListItem>)ViewBag.Statuses, new { #class = "form-control" })
I have a dropdown in View
#Html.DropDownList("GenderAllowed", (SelectList)ViewBag.LocGenederAllowedList, new { #class = "form-control" })
and I am sending list of dropdown through ViewBag, and through model I am sending value that need to be selected in the dropdown.
But the value in dropdown is not selected.
My Controller
[HttpGet]
public ActionResult EditVendorLocation(int VendorLocationID)
{
VendorLocationHandler obj = new VendorLocationHandler();
LocationGrid objLoc = new LocationGrid();
FillGenederAllowed(objLoc);
objLoc = obj.GetVendorLocationForAdmin(VendorLocationID);
return View(objLoc);
}
Function for Viewbag
public void FillGenederAllowed(LocationGrid V)
{
Dictionary<int, string> LocGenederAllowed = EnumHelper.GetGenderStates();
SelectList LocGenederAllowedList = new SelectList(LocGenederAllowed, "key", "value");
ViewBag.LocGenederAllowedList = LocGenederAllowedList;
}
The SelectListItemsyou are passing to the DropDownList have a property Selected. In your ViewModel, set this to true for the item that should be selected initially.
You need this in your controller
ViewBag.LocGenederAllowedList =
new SelectList(db.SomeValues, "Value", "Text",selectedValue);
And in your view
#Html.DropDownList("GenderAllowed",
(SelectList)ViewBag.LocGenederAllowedList, new { #class = "form-control" })
Take a look at this class.
All you need to do is create instances of them and set the Selected property to true for the item you want to be initially selected:
public ActionResult YourActionMethod(...)
{
var selectItems = Repository.SomeDomainModelObjectCollection
.Select(x => new SelectListItem {
Text = x.SomeProperty,
Value = x.SomeOtherProperty,
Selected = ShoudBeSelected(x)
});
ViewBag.SelectListItems = selectItems;
// more code
var model = ...; // create your model
return View(model);
}
You will need this overload of Html.DropDownListFor(...) in order to use this.
You can do it in your controller action like following. Hope it helps.
ViewBag.LocGenederAllowedList = new SelectList(items, "Id", "Name", selectedValue);
dot net fiddle link: https://dotnetfiddle.net/PFlqei
I have come across a problem. I am currently attempting to make a users page in which some of the dropdowns are variable and determined by their 'access level'. I then want to save the data from the view into a list and then handle it in the 'Post' controller method. I found this link about a possible solution (Assign selectlist to dynamically created dropdown in MVC) but I am still running into problems.
Here is my controller code I am using to set up the data that needs to generate the dropdowns:
var permData = db.LabPermissions.Where(x => x.AccessLevel == 1).ToList();
//sets up generic dropdown data used for all dropdowns
ViewBag.DropDownData = new List<SelectListItem>
{
new SelectListItem{ Value = "0",Text = "No"},
new SelectListItem{ Value = "1",Text = "Yes"},
};
ViewModel obj = new ViewModel();
obj.DataFromController = permData;
//other viewmodel data
return("MyView",obj);
I then pass the data to my view which looks like this (this is also how the stack overflow link set up the view)
#for(int i = 0; i < Model.DataFromController.Count(); i++)
{
<div class="row">
<div class="col-md-2">
<b>#Html.DisplayFor(m => m.DataFromController[i].Lab.LabName)</b>
</div>
<div class="col-md-2">
#Html.DropDownListFor(m => m.DataFromController[i].Assigner, (SelectList)ViewBag.DropDownData, "Select One")
</div>
<div class="col-md-8">
</div>
</div>
}
After I get this set up, and run the application, this is the error I receive:
Additional information: Cannot convert type 'System.Collections.Generic.List<System.Web.Mvc.SelectListItem>' to 'System.Web.Mvc.SelectList'
And the error is placed on my #Html.DropDownListFor line of code in my view.
Thank you for any help!
Try creating a new selectlist instead and put your selectlistitems in it.
#Html.DropDownListFor(m => m.DataFromController[i].Assigner,
new SelectList(ViewBag.DropDownData, "Value", "Text", "Select One")
Or, since you got a ViewModel you can add a public property that can hold your selectlistitems.
public class ViewModel
{
public IEnumerable<SelectListItem> DropDownData { get; set; }
}
Controller:
var permData = db.LabPermissions.Where(x => x.AccessLevel == 1).ToList();
var vm = new ViewModel();
var list = new List<SelectListItem>
{
new SelectListItem{ Value = "-1", Text = "Select One", Selected = true},
new SelectListItem{ Value = "0",Text = "No"},
new SelectListItem{ Value = "1",Text = "Yes"}
};
vm.DropDownData = list;
vm.DataFromController = permData;
return View(vm);
View:
#model YourNameSpace.Models.ViewModel
#for(int i = 0; i < Model.DataFromController.Count(); i++){
#Html.DropDownListFor(m => m.DataFromController[i].Assigner, Model.DropDownData)
}
I believe that you're trying to cast SelectListItem to SelectList and that is the reason why you're getting that error. I've done the same feature as a part of my project and I'm taking the values for the dropdownlist from the database.
and for displaying, here is my code(modified a bit based on your model variables
My Controller method
public ActionResult GetDropDownList()
{
List<SelectListItem> dropDownList= new List<SelectListItem>();
using (var context = new assessmentEntities())
{
//getting data from the DB
var result = context.getDataFromDB().toList();
foreach (var item in result)
{
dropDownList.Add(new SelectListItem() { Text = item.Variable1, Value = item.Variable2});
}
ViewBag.DropDownData = dropDownList;
}
return View();
}`
Here is my View
#Html.DropDownListFor(m => m.DataFromController[i].Assigner,, new SelectList(ViewBag.DropDownData, "Value", "Text")
Hope so this works for you
Controller
public void setViewBags()
{
List<GroepModel> groepen = Mapper.Map<List<GroepenWerkvorm>, List<GroepModel>>(db.GroepenWerkvorms.ToList());
var groepmodel = new DropDownModel();
groepmodel.list = new SelectList(groepen, "id", "Naam");
ViewBag.groepmodel = groepmodel;
}
View:
#Html.DropDownListFor(model => model.selectedItem, ViewBag.groepmodel.list as IEnumerable<SelectListItem>,"Selecteer een groep", new { #class = "groepen" })
Each of my elements in groepen has a property called description. I'd like to set the title of each element in the dropdown to the according description, so the user can hover over them to see the description.
I'm assuming I'd probably need JQuery to do this?
var i = 0;
$('.groepen option').each(function(){
$(this).attr('title',// Get the correct description somehow?)
i++;
});
I'm guessing this would probably work, but how do I get the correct description for each element?
The DropDownListFor helper has no support for setting additional attributes on the generated option elements. If you need to set something like a title attribute, you'll need to generate your options manually:
<select id="#Html.IdFor(m => m.selectedItem)" name="#Html.NameFor(m => m.selectedItem)">
#foreach (var groepModel in groepen)
{
<option value="#groepModel.id" title="#groepModel.Description">#groepModel.Naam</option>
}
</select>