How to walk through a SelectListItem Array with Linq - techniques? - linq

Linq – Newbie question:
string[] grades = { "2", "5", "1", "7", "4", "8", "6", "0", "9", "3" };
List<SelectListItem> xValues = new List<SelectListItem>()
{ new SelectListItem
{ Selected = true,
Text = "Select...",
Value = "Select...",
}
};
for (int a = 0; a < 10; a++)
{
xValues.Add(new SelectListItem
{ Selected = false,
Text = grades[a],
Value = grades[a]
}
);
}
My application works very fine up to this point.
xValues contains now 11 elements. Each element contains a "Selected", "Text" and "Value" property. "Selected" is only in the first element set to "true".
The second elements contains a "2" in "Text" and "Value", the third element contains a “5”, the fourth contains a “1” and so on...
Question:
How to set "Selected" to "true" in that xValue element which contains a "5" in the "Text" (and in the "Value") property?
Note, that not the 6th element contains (necessarily) the searched "5"!
I believe it must be something like that:
for (int i = 0; i < ponyValues.Count(); i++)
{
xValues[i].Selected = false;
if (xValues.First().Value == “5”)
{
xValues[i].Selected = true;
}
}
Of course is ".First()" wrong... but what would be correct?

var five = xValues.FirstOrDefault(x=> x.Value == "5");
if (five != null)
five.Selected = true;

SelectListItem item = xValues.Single(item => item.Value == 5);
item.Selected = true;
Please note that this will throw an exception if there isn't exactly one item with a value of 5.

var xValues = grades.Select(g => new SelectListItem
{
Selected = (g == "5")
Text = g,
Value = g
})
.ToList();
xValues.Insert(0, new SelectListItem
{
Selected = false,
Text = "Select...",
Value = "Select...",
});

Thanks to all!
Finally I do this
var isSelected = xValues.FirstOrDefault(x => x.Selected == true);
var mustBeSelected = xValues.FirstOrDefault(x => x.Value == "5");
if ((isSelected != null) && (mustBeSelected != null))
{
isSelected.Selected = false;
mustBeSelected.Selected = true;
}
because I want also to set "Selected" to "false" for the very first element.
Sorry forgot to you tell this ;-)

Related

Linq - List of List

I have a list like the following
var stringCollection = {"X","1", "2","X","5", "10","X","7", "9"}
Now I need a List of List such that each sub list looks like the following
SibList1 = {"X","1", "2"}
SibList2 = {"X","5", "10"}
SibList3 = {"X","7", "9"}
Is it possible using linq.
Regards
Krish
Try this
string[] stringCollection = { "X", "1", "2", "X", "5", "10", "X", "7", "9" };
int index = 0;
var subLists = stringCollection
.Select(x => new { i = (x == "X" ? ++index : index), s = x })
.GroupBy(x => x.i)
.Select(x => x.Select(y => y.s).ToArray())
.ToArray();

MVC ListBox Selected Values

New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })

How to Bind dropdown from anonymous class values

I want to populate a dropdown with values A,Band C.The below code works for create only,not for edit.
ViewBag.UserType = new[] { new SelectListItem { Text = "A", Value = "1", Selected = false }, new SelectListItem { Text = "B", Value = "2", Selected = false }, new SelectListItem { Text = "C", Value = "3", Selected = false } };
So I created an anonymous class. I have an anonymous class like below.
var Roles= new[]
{ new { Id =1,UserType="A" },
new {Id=2,UserType="B" },
new {Id=3,UserType="B" }
};
ViewBag.Type = Roles.ToList();
But i dont know how to fill dropdown in View.
#Html.DropDownListFor(model => model.UserType, ((IEnumerable<SelectListItem>)ViewBag.UserType).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Text),
Value = option.Value.ToString(),
Selected = (Model != null) && (option.Value == (Model.UserType).ToString())
}),"Select")
What changes should i make in the view
Add following properties to your ViewModel class -
public SelectList Roles
{
get
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem
{
Value = "1",
Text = "A",
});
items.Add(new SelectListItem
{
Value = "2",
Text = "B",
});
items.Add(new SelectListItem
{
Value = "3",
Text = "C",
});
return new SelectList(items, "Value", "Text");
}
}
public int SelectedRole { get; set; }
and bind in View as follows -
#Html.DropDownListFor(model => model.SelectedRole, Model.Roles)

how to use jstree ondemand with mvc3 razor

I have to display a treeview .But it will take much time, that's why I want to load this treeview on demand.At the first I want just display first level, and repeating that level by level.
This is the view
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1) {
url = "/TreeView/GetCollectionWS/source";
}
else {
nodeId = node.attr('id');
url = "/TreeView/GetCollectionWS/" + nodeId;
}
return url;
},
"type": "POST",
"dataType": "json",
"contentType": "application/json charset=utf-8"
}
},
checkbox: {
real_checkboxes: true,
checked_parent_open: true
},
plugins: ["themes", "json_data", "ui", "checkbox"]
});
this is the controller
public virtual ActionResult GetCollectionWS(string root)
{
int? nodeId = (root == source) ? (int?)null : Convert.ToInt32(root);
Object[] liste = new Object[100];
liste = DSClient.Views.Traitement.getTop(nodeId);
List<TreeViewNode> nodes = new List<TreeViewNode>();
for (int i = 0; (i < liste.Length && liste.ElementAt(i) != null);i++ )
{
bool leaf = false;
nodes.Add(new TreeViewNode()
{
id = Convert.ToString(DSClient.Views.Traitement.GetNodeId(liste.ElementAt(i))),
text = liste.ElementAt(i).Handle,
classes = leaf ? "file" : "folder",
hasChildren = !leaf
});
}
return Json(nodes);
}
when I try a breakpoint on the line return Json(nodes); I remarque that nodes contains
at the first {id=0,text=Collection-10,classes=folder,haChildren=false}
the view display nothing.Please, can any one help me??
public virtual string GetCollectionWS(string id)
{
Object[] liste = new Object[100];
client = new DSServiceClient();
if (id == "source")
{
Collection[] _top = new Collection[100];
client.Open();
_top = client.GetTopCollections();
client.Close();
for (int i = 0; i < _top.Length; i++)
{
DSClient.Controllers.Object obji = new DSClient.Controllers.Object();
obji.Handle = _top[i].Handle;
obji.Name = _top[i].Title;
liste[i] = obji;
}
}
else
{
client = new DSServiceClient();
client.Open();
Tree tree = client.GetTreeView(id);
client.Close();
liste = tree.listObjects;
}
var recursiveObjects = FillRecursive(liste);
string myjsonmodel = new JavaScriptSerializer().Serialize(recursiveObjects);
return myjsonmodel;
}
private static List<RecursiveObject> FillRecursive(Object[] flatObjects)
{
List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
for (int i = 0; (i < flatObjects.Length && flatObjects.ElementAt(i) != null); i++)
{
recursiveObjects.Add(new RecursiveObject()
{
data = flatObjects.ElementAt(i).Name,
id = flatObjects.ElementAt(i).Handle,
attr = new FlatTreeAttribute { id = flatObjects.ElementAt(i).Handle, selected = false },
children = null,
state = "closed"
});
}
return recursiveObjects;
}
Now I want to send the text and Id of nodes selected to my controller.
<script type="text/javascript">
var divId = [];
var divText = [];
$('#idjstree').value=function GetIDs() {
divId = [];
divText = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
(function () {
divId.push(this.id);
divText.push($(this).children('a').text());
});
return (divId);
}</script
and this is in the view
#:<div id="onflycheckboxes"></div>
#:<input type="hidden" id="idjstree" name="idjstree" value="" />
but always I get idjstree="" when I do a breakpoint on the post of create.But the function GetIDs() is correct.
What can I do please?

Avoid duplicate entries in List<SelectListItem>

How can I check that List< SelectListItem> doesn't contain or insert any duplicates in Mvc3. I have tried with !Contains
Thanks
Try this:
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "Some Text", Value = "Some Value" });
list.Add(new SelectListItem { Text = "Other Text", Value = "Other Value" });
var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(!list.Any(l => l.Value == selectListItem.Value)
{
list.Add(selectListItem);
}
.Contains() compares if the object reference, not the Value property
var list = new List<SelectListItem>();
var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(list.FirstOrDefault(t => t.Value != selectListItem.Value) == null)
{
list.Add(selectListItem);
}

Resources