Binding the dropdownlist to the mvc view - c#

I am trying to bind the dropdown list to the data-set coming from the data context class in mvc 6. I wrote a function to get the populated list but unable to reproduce the same using razor. Here's what I have so far. Please note that I have not created a model yet. trying to make use of the generated POCO class from the database scaffolding.
function on Layout.cshtml
#functions{
public List<HSIP.Entities.StateDetails> function1()
{
// protected readonly HSIP.Entities.HSIPContext context;
HSIP.Entities.HSIPContext hsipcontext = new HSIP.Entities.HSIPContext();
List<HSIP.Entities.StateDetails> getstatelist = (from s in hsipcontext.StateDetails
select new HSIP.Entities.StateDetails
{
StateDesc = s.StateDesc,
StateCode = s.StateCode,
StateAbbr = s.StateAbbr
}).ToList();
//SelectList list = new SelectList(getstatelist, "Region", "StateCode", "StateAbbr", "StateDesc");
return getstatelist;
}
}
Razor syntax:
#Html.DropDownList("StateDesc", #function1(), "Please select State Name");
The Razor syntax throws an error: there is no argument given that corresponds to the required formal parameter 'htmlattributes' of IHTMLHelper.Dropdownlist(string, IEnumerable, string, object).
can someone please point me in the right direction.
Thanks,
Hari

I am prefer do this:
In a controller/Model:
using System.Web.Mvc;
public List<SelectListItem> DropdownListFilter()
{
var listitem = new List<SelectListItem>();
listitem.Add(new SelectListItem { Text = "Dropdown1", Value = "0", Selected = true });
listitem.Add(new SelectListItem { Text = "Dropdown2", Value = "1", Selected = false });
listitem.Add(new SelectListItem { Text = "Dropdown3", Value = "2", Selected = false });
return listitem;
}
When I Load in the ActionResult Just add this following Line:
ViewBag.FilterDropdown = ar.DropdownListFilter().ToList();
And in the view you have to call Filter dropdown like this:
#Html.DropDownList("FilterDropdown")
Hope this help.

Firstly use a SelectListItem in your controller and pass it to your view.Then use it in Razor syntax to populate the dropdown.
List<SelectListItem> stateList = (from s in hsipcontext.StateDetails
select new HSIP.Entities.StateDetails
{
StateDesc = s.StateDesc,
StateCode = s.StateCode,
StateAbbr = s.StateAbbr
}).ToList();
View:
#Html.DropDownListFor("StateDesc", stateList ,"Please select State Name")

Related

How can i combine two object fields in Object List into one DropDown in mvc

Actually i have a action which generates a viewbag in it . i am passing an object List in my ViewBag . Now in the View i want to create a dropdown through my viewbag object which i need two fields as a combined in dropdown List in mvc . e.g. my ServiceList.field1 ,ServiceList.field2 . i want both these fields combined in dropdown .
public ActionResult Add()
{
List<service> ServiceList = new List<service>();
ServiceList = GetService();
ViewBag.BackUPList = ServiceBackupList;
return View();
}
and my view contains
#Html.DropDownList("name", (SelectList)ViewBag.BackUPList, new { #class =
"form-control" })
how to combine my both fields and show in dropDown grouped separately.
e.g.
ServiceList.field1
ServiceList.field1
ServiceList.field2
ServiceList.field2
You can generate a new collection in which you concatenate two properties in to one and then construct a SelectList like:
ServiceList = GetService();
var dropDownList = ServiceList.Select(x=> new
{
Id = x.IdField,
Name = x.Field1.ToString() + x.Field2.ToString()
}).ToList();
ViewBag.BackUPList = new SelectList(dropDownList,"Id","Name");
EDIT:
As per edited question you need to generate two collection and then concatenate:
var fieldList = ServiceList.Select(x=> x.IdField1)
.Concat(ServiceList.Select(x=> x.IdField2)).ToList();
and then create a SelectList and put in ViewBag :
ViewBag.BackUPList = fieldList.Select(x =>
new SelectListItem()
{
Value = x,
Text = x
}).ToList();
and in View :
#Html.DropDownList("name",
ViewBag.BackUPList as IEnumerable<SelectListItem>,
new { #class = "form-control" })

default value for DropDownListFor helper mvc 5

I have this part of code that runs very well:
merge1.Statuses = db.JobStatus.Select(s => new SelectListItem
{
Value = s.JobStatusID.ToString(),
Text = s.JobStatusName
}).ToList();
Now, I want to add a default value that is a dynamic value, depending on the database. So, I tried something like:
private SelectListItem statuses(string defaultStatus)
{
db.JobStatus.Select(s => new SelectListItem
{
Value = s.JobStatusID.ToString(),
Text = s.JobStatusName,
defaultStatus
}).ToList();
return ???
}
So, I have marked red on defaultStatus.
Thanks in advance
I would do it like this
private IEnumerable<SelectListItem> statuses(string defaultStatus)
{
return db.JobStatus.Select(s => new SelectListItem
{
Value = s.JobStatusID.ToString(),
Text = s.JobStatusName,
Selected = s.JobStatusName == defaultStatus
}).ToList();
}
Also change the return type so you can bind it to a select list in the view.

How exactly does the selected value of a selectList work?

I need to create a dropdown list and I'm doing this by creating a new SelectList based on a model. Here is how I am trying to do this:
#Html.DropDownListFor(model=>model.SelectedStudio, new SelectList(Model.Studios, "Id", "Name", Model.Studio)
I see from the class signature that the last parameter is object selectedValue. I have now tried many variations, trying to pass a string there, an object, etc. but when I compile the program, the selected value for the dropdown list is never set to what I want.
Can anyone explain how this works?
EDIT: I don't know if this is important, but the Id of Studio is of type ObjectId (from the MongoDB C# Driver)
I think your not setting for the selected value on new SelectList
your code should be
#Html.DropDownListFor(model=>model.SelectedStudio, new SelectList(Model.Studios, "Id", "Name", [Defualt value])
the reason it not give the error becuase it is object. and your setting up your IEnumerable list. so it is object. see the following link
http://msdn.microsoft.com/en-us/library/dd492553(v=vs.118).aspx
Try this:
#Html.DropDownListFor(model=>model.SelectedStudio, new SelectList(Model.Studios, "Id", "Name", Model.Studio.Id)
this is how u keep a value selected in drop down
#Html.DropDownList("statussearch", new List<SelectListItem>
{
new SelectListItem { Text = "text1", Value = "1", Selected = Studio.IsSelected.HasValue ? Studio.IsSelected.Value : false},
new SelectListItem { Text = "text2", Value = "2"},
new SelectListItem { Text = "text3", Value = "3"},
}, "Select Status")
IsSelected is a field in your DB wch states wch value to be selected.
this will work fine for your requirement
#foreach (var value in studios)
{ #Html.DropDownList("statussearch", new List<SelectListItem>
{new SelectListItem { Text =value.prop1, Value = "1" },new SelectListItem { Text = value.prop2, Value = "2"},new SelectListItem { Text = value.prop3, Value = "3"},}, value.proptobeselected)}

how to add a selectlistitem to a selectlist

I have the following select list
public SelectList StaffList { get; set; }
I am assigning it the following,
inspectorCorrespondences.StaffList = new SelectList(userDetails, "Id", "FullName");
but I want to add in another SelectList item
var systemGeneratedUser = new SelectListItem() { Value = "-1", Text = "System Generated" };
how do I do that?
This isn't necessarily the most elegant solution, but you'll need to cast the SelectList's items to a list of SelectListItems if you want to add another SelectListItem.
var myItems = new List<SelectListItem>();
myItems.Add(new SelectListItem() { Text = "AA", Value = "11" } );
var mySelectList = new SelectList(myItems);
((List<SelectListItem>)mySelectList.Items).Add(new SelectListItem() { Text = "BB", Value = "22" });
According to the documentation, it looks like you need to initialize the SelectList with the values instead of adding them. Passing an enumerable of SelectListItem to the constructor appears to be the expected way.
It looks like you're already doing that in the sense that userDetails is already an enumeration? If so, what type of enumeration is it? You may need to add a line or two of code to transform it to an enumeration of SelectListItem objects, add yours to that, and then use that to initialize the SelectList. Maybe something like this:
var listItems = userDetails.Select(u => new SelectListItem { Value = u.Id, Text = u.FullName }).ToList();
listItems.Add(new SelectListItem() { Value = "-1", Text = "System Generated" });
// or perhaps .Insert() at position 0 instead?
inspectorCorrespondences.StaffList = new SelectList(listItems, "Value", "Text");

Issue with MVC2 DropDownListFor, only displaying the class-name

Good day,
I have this problem with Html.DropDownListFor which I can't seem to work out.. It gives me the correct number of options, if I do a breakpoint in the code where it is supposed to render the list, the "SelectItemList" object contains the items with correct values, but the actual HTML it spits out is the following:
<select id="Reason_ReasonId" name="Reason.ReasonId"><option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>
The module containts this:
public SelectList ReasonList
{
get
{
SelectList selectList;
List<SelectListItem> selectItems;
using (var db = new EscalationDataContext())
{
var reasons =
db.Reasons
.OrderBy(r => r.Reason1)
.Select(r => new SelectListItem
{
Value = r.ReasonId.ToString(),
Text = r.Reason1
});
selectItems = reasons.ToList();
selectList = new SelectList(selectItems);
}
return selectList;
}
}
The controller just creates a default instantiation and sets the default value:
public ActionResult Create()
{
EscalationModel model = new EscalationModel
{
Reason = new Reason { ReasonId = new Guid("598c28c2-877a-44fa-9834-3241c5ee9355"), Reason1 = "Taken too long" },
ActionedDate = DateTime.Now
};
return View(model);
}
Last but not least, the view:
<%: Html.DropDownListFor(m => m.Reason.ReasonId, Model.ReasonList) %>
Any ideas why it behaves like this? As I said, in the actual code (in the view) I have the correct values, but.. It doesn't like me.. Any help would be greatly appreciated, thanks in advance!
Ok.. It seems you had to specify which variable in SelectListItem was used for "Value" and which was used for "Text"..
selectList = new SelectList(selectItems);
Became..
selectList = new SelectList(selectItems, "Value", "Text");
Which seems to have done the trick!

Categories