add into selectlist an item only if it doesn't exist into razor - razor

I want to create selectlist dynamically by traversing child nodes with 'language' property. So, want to add this property value as a select list item only if it is not added previously.
I have following code.
#{
var litem = new List<SelectListItem>();
litem.Insert(0, new SelectListItem { Selected = true, Text = "All", Value = "" });
foreach (var i in Model.Content.Children.Where("Visible"))
{
//if (i.GetProperty("language").Value != "")
if (i.GetProperty("language").Value != "")
{
string langstr = i.GetProperty("language").Value.ToString();
SelectListItem item = new SelectListItem { Selected = false, Text = langstr, Value = langstr };
if ((!(litem.Contains(item))))
{
litem.Add(item);
}
}
}
var slang=new SelectList(litem);
#Html.DropDownList("drpLang", #slang, new { #class = "dropdown"})
}
But it is not able to check the same item present in list. What is going wrong?

if i understand you correctly, problem that litem contain duplicate,
this because you create new instance of object item and than check is list contain new instance (you not check for same property, you check for exactly same object).
change this line:
if ((!(litem.Contains(item))))
for something like this:
if (litem.All(i => i.Value != item.Value))
or if you need unique pair:
if (litem.All(i => i.Value != item.Value && i.Text!= item.Text))
also recommend move all login in controller and use viewbag for DropDownList

Related

#Html.DropDownListFor is showing a textbox before loaded

I have some problems with a multiple dropdownlist, while loading its showing a textbox and them it load the dropdownlist control:
this is the code in the View:
#Html.DropDownListFor(m => #m.SelectedInfractionsId,
new MultiSelectList(Model.InfractionList, "Value", "Text", #Model.SelectedInfractionsId),
new {
id = "SelectedInfractionsId",
#class = "form-control multiselect-dropdown",
multiple = "true",
data_placeholder = "Select Users"
})
This is the code in the Controller:
List<SelectListItem> Listofinfractions = new List<SelectListItem>();
var infractions = _context.InfractionsCategories.OrderByDescending(x => x.Id == 1);
foreach (var infraction in infractions)
{
Listofinfractions.Add(new SelectListItem()
{
Value = infraction.Id.ToString(),
Text = infraction.Name
});
}
Listofinfractions.Insert(0, new SelectListItem()
{
Text = "----Select----",
Value = string.Empty
});
Looks like the image down below:
DropDownListFor control while is loading
once is loaded the control looks like :
DropDownListFor control when is loaded

How to get value of selected index in combo Box when user select the value from it in flex

Hi I have created a comboBox dynamically and Since I'm new to Flex I have no idea how to get the selected value from combo box when user select a value from combobox dropdown
Below is my code
var comboBox:ComboBox = new ComboBox();
comboBox.dataProvider = field.getValues();
comboBox.width = "50";
comboBox.prompt = "Test";
comboBox.selectedIndex = -1;
Could someone help me out in order to identify how I'll be able to get value of a selected index when user will select the value from dropdown of combo box ?
Even a sample example will help me !!
Thanks in Advance.....!!
You can use comboBox.selectedItem.
Remember to check for null as selectedItem will return null if it is not set.
comboBox.addEventListener(ListEvent.CHANGE, comboBox_change, false, 0, true); //weak listener
private function comboBox_change(event:Event):void {
var comboBox:ComboBox = event.target as ComboBox
var item:MyClass = comboBox.selectedItem as MyClass
if(item) {
//do what you need to do
}
}
You can do like following way:
var comboBox:ComboBox = new ComboBox();
comboBox.dataProvider = field.getValues();
comboBox.width = 50;
comboBox.prompt = "Test";
comboBox.selectedIndex = -1;
comboBox.addEventListener(ListEvent.CHANGE, onChange);
panel.addChild(comboBox);
private function onChange(event:Event):void
{
trace(event.currentTarget.selectedItem); //Here you get the selected item.
}
Hope it helps.

DropDownListFor selected value not working

So I have this in my view(I have broken it out into a foreach so I could debug it properly). And according to the objects that are created it looks good. I get 1 item that has the selected true.
#{
var useritems = new List<SelectListItem>();
foreach (var si in Model.UserList)
{
if (Model.CurrentUser.Id.Equals(si.Id))
{
useritems.Add(new SelectListItem { Selected = true, Text = si.Username, Value = si.Id.ToString(CultureInfo.InvariantCulture) });
}
else
{
useritems.Add(new SelectListItem { Text = si.Username, Value = si.Id.ToString(CultureInfo.InvariantCulture) });
}
}
}
What I want to do here is check for the current(logged on) user and set the select default to him/her.
#Html.DropDownListFor(model => model.Creator, useritems, new { id = "CreatorDDL", })
This does not however set any of the objects in useritems to selected. Even tho in the debugger it shows that 1 item has selected: true
Somehow it just shows the first item in the list.
Any ideas? or am I just tired and missing something really easy?
Set model.Creator value in addition to Selected in SelectList.
model.Creator = Model.CurrentUser.Id;
It's better to do such things in your Controller, not in your View.

Set initial combobox selection DevExpress Razor

I simply want to have the "Area" value (which is one of the items) be selected when the view appears. This is what I have:
#Html.DevExpress( ).ComboBox( settings =>
{
settings.Name = "cmbFieldLevel";
settings.CallbackRouteValues = new { Controller = "Equipment", Action = "FieldLevelPartial" };
settings.Properties.ValueType = typeof( string );
settings.Properties.TextField = "AreaName";
settings.Properties.ValueField = "AreaID";
settings.Properties.EnableClientSideAPI = true;
settings.ClientSideEvents.DataBound = "function( s, e ){ cmbFieldLevel.SelectedItem = "Area"; } ";
}).BindList(FieldLevel.GetAreaFilters()).GetHtml()
Any clues?
2 ways I can think of.
If you change your ComboBox to ComboBox for you can specify the model's value
like so
#Html.DevExpress().ComboBoxFor(x => x.ParamOrderNo, settings =>
{
settings.Properties.ValueField = "OrderNo";
settings.Width = 200;
settings.Properties.TextField = "Name";
}).BindList(CeduleProductionMVC.ViewModels.ViewModelCeduleGlobale.GetCommandes()).GetHtml()
Also, you can set the SelectedIndex, if your combolist content is fixed, the index might always be the same everytime all the time. Also, If you list is not fixed, you might be able to make a method to retrieve the index and set in after that.

Slickgrid - Column Definition with Complex Objects

I have a Java object where the person object contains a displayName object. I have converted it to a JSON object for my JSP. The data looks like the following:
var people = [
{"id":52959,"displayName":{"firstName":"Jim","lastName":"Doe","middleName":"A"},"projectId":50003,"grade":"8","statusCode":"A","gradYear":2016,"buyer":false},
{"id":98765,"displayName":{"firstName":"Jane","lastName":"Doe","middleName":"Z"},"projectId":50003,"grade":"8","statusCode":"A","gradYear":2016,"buyer":true}
];
I want to bind my columns to the name properties that reside within the displayName object, but I am cannot get the column definition to recognize where the data resides. Here is an example of my firstName column definition:
{id: 'displayName.firstName', field: 'displayName.firstName', name: 'First Name',
width: 110, sortable: true, editor: TextCellEditor, formatter: SpaceFormatter,
cssClass: '', maxLength: 250, editable: true}
The view does not render the names although the data is there. Is it possible to bind a column to an object property that resides within another object? If so, what am I doing wrong?
Slickgrid doesn't support this capability by default, but you can workaround it by adding custom value extractor to your options object:
var options = {
dataItemColumnValueExtractor: function(item, columnDef) {
var names = columnDef.field.split('.'),
val = item[names[0]];
for (var i = 1; i < names.length; i++) {
if (val && typeof val == 'object' && names[i] in val) {
val = val[names[i]];
} else {
val = '';
}
}
return val;
}
}
var grid = new Slick.Grid($("#slickgrid"), data, columns, options);
The code is tested with slickgrid 2.0 and is working just fine. Unfortunately seems that slickgrid code is a bit inconsistent and editors don't take into account this option, so this solution is usable only if you will display the data without editing.
I know this is a bit old... but my work around is to do a pre-process on my items. Basically, flattening the model out:
var preProcessItems = function (items) {
var newItems = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
item['firstName'] = item['displayName']['firstName'];
newItems[i] = item;
}
return newItems;
};
/// when the value is updated on the flat structure, you can edit your deep value here
var fNameFormatter = function (row, cell, value, columnDef, dataContext) {
// datacontext.displayName.firstName = value;
return value ? value : "";
};
This problem seems to be more a of a data modeling issue though.