DropDownListFor selected value not working - html

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.

Related

two-way data binding of input checkbox element

My problem goes like this:
I have this array and variable:
// the options
public items = [{id: 1, main: true}, {id: 2, main: false}, {id: 3, main: false}];
// the selected option
public selectedItem = this.items[0];
and my html looks something like this:
<select id="itemOptions"
name="itemOptions"
[(ngModel)]="selectedItem">
<option *ngFor="let item of items" [ngValue]="item">{{item.id}}</option>
</select>
<input id="mainItem"
name="mainItem"
type="checkbox"
[(ngModel)]="selectedItem.main"
(ngModelChange)="setMain()" >
and the setMain function looks like this:
setMain() {
for(let item of this.items){
//set all items` main to false if they are not the selected item
if(this.selectedItem.id != item.id){
item.main = false;
}
//if it is the selected item, set it as the main item
else if(this.selectedItem.id == item.id){
item.main = true;
}
}
}
the point here is there must be a main item at all times.
but when I select the main item and uncheck it the function works great and the main stays true, but the checkbox is still unchecked.
I've read this post and some more but did not found something that look like my case, nor clues for an answer.
As I understand the two-way data binding, when I clicked the checkbox it changed the value of my selectedItem.main to false. but then the setMain is called and sets it back to true. Why the checkbox doesn't become checked back?
Any way of achieving this would be great :).
note: I don't want to set the checkbox checked to true manually. I want to understand why the two-way data binding doesn't handle this case.
Solution to your situation
is put all the code of setMain within setTimeout :
setMain() {
setTimeout(() => {
for(let item of this.items){
//set all items` main to false if they are not the selected item
if(this.selectedItem.id != item.id){
item.main = false;
}
//if it is the selected item, set it as the main item
else if(this.selectedItem.id == item.id){
item.main = true;
}
}
})
}
WORKING DEMO
For more detail please check : Angular 2 - Checkbox not kept in sync
I have tried as below please check is it that you required?
<input id="mainItem"
name="mainItem"
type="checkbox"
[(ngModel)]="selectedItem.main"
(click)="setMain($event.target.value)" >
setMain(value) {
for(let item of this.items){
//set all items` main to false if they are not the selected item
if(this.selectedItem.id != item.id){
item.main = false;
}
//if it is the selected item, set it as the main item
else if(this.selectedItem.id == item.id){
item.main = !value;
}
}
}

add into selectlist an item only if it doesn't exist into 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

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.

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.

adding a new row only when the last row in modified

Problem description:
I have a table with three rows. The first row contains a drop down. When a user selects a drop down option, a new row should be generated beneath the current last row. How can I tweak this code to such that a new row is generated only when the user selects a drop down option of the current last row, and not any other row?
JSFiddle: http://jsfiddle.net/JPVUk/13/
var ViewModel = function() {
var self = this;
self.items = ko.observableArray([{comment:'first comment', amount:0}]);
self.addNewItem = function(){
self.items.push(new Item('',0));
};
}
var Item = function(comment, amount) {
var self = this;
self.comment = ko.observable(comment);
self.amount = ko.observable(amount);
};
vm = new ViewModel()
ko.applyBindings(vm);
What I am struggling to do:
So, since I want to bind the change event to the last row, here's how I am approaching it:
<select class="input-small" data-bind="items()[items.length-1] ? event: { change: $root.addNewItem }">
This is however not working. Any ideas folks ?
Can't you just past the row that causes the event to fire to your handler and check it there?
Something like this:
<select class="input-small" data-bind="event: { change: $root.addNewItem }">
And then:
self.addNewItem = function(row){
if (row == self.items()[self.items().length - 1]) {
self.items.push(new Item('',0));
}
};
http://jsfiddle.net/JPVUk/14/
I'm not sure if jQuery was acceptable so this just uses DOM. Basically use the event object passed to knockout. Traverse a little dom and determine is the event target is a child of the last row in the parent table:
var tableRow = event.target.parentNode.parentNode,
body = tableRow.parentNode,
nodes = body.childNodes,
children = [];
for (var i = 0; i < nodes.length; i++) {
// remove non-element node types. ie textNodes, etc.
if (nodes[i].nodeType === 1) {
children.push(nodes[i]);
}
}
if (tableRow === children[children.length - 1]) {
self.items.push(new Item('', 0));
}