Unable to add images to Telerik Tree View - asp.net-mvc-4

Here I'm going to add Telerik Tree View using MVC 4.Tree is populating.But when i tries to add Image, then it failed..
My code goes here
#(Html.Telerik().TreeView()
.Name("TreeView")
.BindTo(Model, mappings =>
{
mappings.For<myMVCapp.Models.ProjectTree>(binding => binding
.ItemDataBound((item, node) =>
{
if (item.Text == "News Project")
{
item.ImageUrl = "~/Content/Images/myimg.png";
}
item.Text = node.RootNodeText;
})
.Children(node => node.ChildNodes)
);
mappings.For<MyEntityModel.Project>(binding => binding
.ItemDataBound((item, subNodes) =>
{
item.Text = subNodes.ProjectName;
}));
})
)
Any one have idea about how to add image ?

You try to compare item.Text with something before giving it a value. So inside your if expression the item.Text will be always null so your item.ImageUrl = ... line won't be executed.
So do the value assignment before the if:
item.Text = node.RootNodeText;
if (item.Text == "News Project")
{
item.ImageUrl = "~/Content/Images/myimg.png";
}
Or use the node.RootNodeText in your if:
if (node.RootNodeText == "News Project")
{
item.ImageUrl = "~/Content/Images/myimg.png";
}
item.Text = node.RootNodeText;

Related

VueDraggable of Sortable is not working properly and send the choosed item to the first on init

I'm using Vue.Draggable in my Nuxt project. i used it in some pages and component and every thing is fine. but on one of my pages it gives me a silly problem!! when page is loaded, it send the chosen item to the first!! after that every thing works fine! even if i choose and unchoose without moving, things works fine!!
i tried to check if the choosed went to first of array move it again properly. it worked when the chosen item is the first if array but if i choose others than first, on 2nd try it move another item too!!
so i'm kinda stuck.
here is the code:
btw there are some variables and methods that u cant find them like cmsListItems. they are globally added to my project
template:
<draggable v-model="myItemsArray" #end="onEnd" #choose="onChoose" #unchoose="onUnChoose" v-bind="getOptions()">
<transition-group type="transition" name="sortable_transition">
<categorylistcard v-for="(category, index) in cmsListItems"
listtype="cat"
:key="category.id"
:cat="category"
:index="index"
:showforsub="showForSub"
:parentarr="parentArr"
#addnewsub="addNewCat()"
:sub="true"
:sublvl="true"
:sortable="true"
:btntitle="lang.addsubcat"
/>
</transition-group>
</draggable>
script:
export default {
data(){
return{
oldIndex: '',
newIndex: '',
dragOptions: {
ghostClass: "sortable_ghost",
chosenClass: "sortable_chosen",
handle: ".sortable_handle",
disabled: false
},
isMoved: false,
myItemsArray: [],
originalItemsArray: [],
choosedItem: null
}
},
methods:{
// ***** Reorder By Sorting *****\\
this.isMoved = true
this.oldIndex = event.oldIndex
this.newIndex = event.newIndex
console.log(this.myItemsArray[this.oldIndex])
console.log(this.myItemsArray[this.newIndex])
if(this.oldIndex !== this.newIndex){
this.dragOptions.disabled = true
let response = await this.axiosGet(`category/reorder/${this.originalItemsArray[this.oldIndex].id}/${this.originalItemsArray[this.newIndex].id}`)
if(this.resOk(response.status)){
this.noty(ALERT_TYPE[1], 'ok')
this.originalItemsArray = this.myItemsArray
this.isMoved = false
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
this.setCmsListItems(this.myItemsArray)
// this part is my defected solution
setTimeout(() => {
if(this.myItemsArray[this.oldIndex].id === this.choosedItem.id || this.myItemsArray[0].id === this.choosedItem.id){
let arrayOfItems = [...this.originalItemsArray]
arrayOfItems.shift()
arrayOfItems.splice(this.newIndex,0,this.choosedItem)
this.setCmsListItems(arrayOfItems)
this.myItemsArray = [...this.cmsListItems]
}
}, 50);
// --------------------
}else{
this.isMoved = false
this.myItemsArray = this.originalItemsArray
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
}
}else{
this.isMoved = false
this.myItemsArray = this.originalItemsArray
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
}
},
addClassToMovedItems(index){
if((index == this.oldIndex || index == this.newIndex) && this.isMoved == true){
return 'sortable_moved'
}else{
return ''
}
}
},
async fetch(){
this.btnLoading = true
let response = await this.axiosGet(`categories/admin/0/1`)
if(this.resOk(response.status)){
if(this.notEmpty(response.data)){
this.setCmsListItems(response.data.items)
this.myItemsArray = [...this.cmsListItems]
this.originalItemsArray = [...this.cmsListItems]
}
this.btnLoading = false
}
},
}
I kinda hacked through it, so i don't recommend it!!
I got the chosen item with #choose and in my #end checked if first index of my array is the chosen item, unshift array and add the chosen to newIndex with splice() like bellow:
setTimeout(() => {
if(this.myItemsArray[this.oldIndex].id === this.choosedItem.id || this.myItemsArray[0].id === this.choosedItem.id){
let arrayOfItems = [...this.originalItemsArray]
arrayOfItems.shift()
arrayOfItems.splice(this.newIndex,0,this.choosedItem)
this.setCmsListItems(arrayOfItems)
this.myItemsArray = [...this.cmsListItems]
this.choosedItem = null
}
}, 1);

Cannot modify managed objects outside of a write transaction - React Native, Realm

onPressFavourites(item) {
let realm = Realm.open({
path: RNFS.DocumentDirectoryPath +'/trees.realm',
schema: [sightingSchema, treeSchema],
schemaVersion: 7,
}).then(realm => {
if(item.favourites === 0) {
realm.write(() => {
item.favourites = 1;
item.favouritesColour = '#91b54d';
});
} else {
realm.write(() => {
item.favourites = 0;
item.favouritesColour = 'transparent';
});
}
});
alert(item.favourites)// Update a property value
}
I am trying to update an object in the Realm when a button is clicked however I get the error
"Possible Unhandled Promise Rejection (id: 0):
Error: Cannot modify managed objects outside of a write transaction."
This code was working a couple days ago but is now throwing the above error.
I am still learning React Native and Realm but from my understanding and following examples and the Realm docs, I am using the correct code so it should work.
EDIT
Seems the realm and write transactions were fine.
We were able to find a roundabout way to fix it however now the updates don't display until the app is refreshed.
It seems the error Possible Unhandled Promise Rejection (id: 0):
Error: Cannot modify managed objects outside of a write transaction. was produced when using the argument item to define the chosen Realm Object. However, if we create a variable related to the item, it doesn't produce that error. Any ideas why this would happen?
onPressFavourites(item) {
//console.log(realm);
let realm = Realm.open({
path: RNFS.DocumentDirectoryPath +'/trees.realm',
schema: [sightingSchema, treeSchema],
schemaVersion: 7,
}).then(realm => {
let trees = realm.objects('TreeInfo');
for(var i=0; i<trees.length;i++){
if(trees[i].commonName == item.commonName){
var chosen = trees[i];
break;
}
}
console.log(chosen);
if(item.favourites === 0) {
realm.write(() => {
//item.favourites = 1;
//item.favouritesColour = '#91b54d';
chosen.favourites = 1;
chosen.favouritesColour = '#91b54d';
});
}
else {
realm.write(() => {
chosen.favourites = 0;
chosen.favouritesColour = 'transparent';
});
}
});
alert(item.favourites)// Update a property value
}
EDIT
render() {
var treeList = this.state.trees;
console.log(treeList);
const {navigate} = this.props.navigation;
//var tree = treeList[0];
return(
<Container>
<Header searchBar style={styles.searchBar}>
<Item style={styles.searchBarInner}>
<Icon name="ios-search" />
<Input placeholder="Search" />
</Item>
</Header>
<List dataArray={treeList}
renderRow={(item) =>
<ListItem style={styles.ListItem} button={true}>
<ListButton item={item}
onSelect={(item) => this.saveTreeInfo(item)}
onSelectFavourites={(item) => this.onPressFavourites(item)
}
/>
</ListItem>
}
>
</List>
</Container>
);
}
Above is where item is being passed to the onPressFavourites function. item is being generated from an array of Realm Objects treelist and displayed in a list.
The treelist array comes from the variable this.state.trees which is displayed below.
filterContent(){
Realm.open({
path: RNFS.DocumentDirectoryPath +'/trees.realm',
schema: [sightingSchema, treeSchema],
schemaVersion: 7,
}).then(realm => {
let trees = realm.objects('TreeInfo');
let length = trees.length;
let treeRealm = trees.sorted('commonName');
console.log(this.state.leafEdges);
if (this.state.leafEdges === 'smooth') {
var smoothLeaf = treeRealm.filtered('leafEdges CONTAINS "Smooth"');
this.setState({trees:smoothLeaf});
}
if (this.state.leafEdges === 'toothed') {
var toothedLeaf = treeRealm.filtered('leafEdges CONTAINS "Toothed"');
this.setState({trees:toothedLeaf});
}
if (this.state.leafEdges === 'notsure') {
this.setState({trees:treeRealm});
}
else if (this.state.leafEdges === 'null') {
this.setState({trees:treeRealm});
}
});
}
Answer in English:
The trees has something about realm, so you cannot change it. Just copy a new Array like this:
let trees = realm.objects('TreeInfo');
var arr=[];
for (let i = 0;trees && i < trees .length; i++) {
var item=trees[i];
var item2={
id: item.id,
....
}
arr.push(item2);
}
You should improve the syntax
let order = {...bla, bla,bla}
realm.write(() => {
realm.create("order", order);
});
这个trees 里面关联了realm里的一些东西,所以不能改变,要重新复制一个数组,像这样
let trees = realm.objects('TreeInfo');
var arr=[];
for (let i = 0;trees && i < trees .length; i++) {
var item=trees[i];
var item2={
id: item.id,
....
}
arr.push(item2);
}

Using system.linq.lookup values for dropdownfor mvc 4

In MVC 4 I am using razor to get items from collection and assign it to a var. The var is of type
{System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping}
This is my code
var ChairList = Model.Interviewers.Where(d => d.LocKey == Convert.ToString(location.LocationKey) && d.IsChair && d.Date == date.Date).GroupBy(x => new { x.FullDetails, x.InterviewerId, x.Preference }).ToList();
And how it looks in watch:
- ChairList Count = 1 System.Collections.Generic.List<System.Linq.IGrouping<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>>
- [0] {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping} System.Linq.IGrouping<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer> {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping}
+ [System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping] {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping} System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping
- Key { FullDetails = "TEST - Richard Jackson - (80020937)", InterviewerId = {ff1efad7-7176-4fab-a1bb-30f6656c8880}, Preference = "Available" } <Anonymous Type>
FullDetails "TEST - Richard Jackson - (80020937)" string
+ InterviewerId {ff1efad7-7176-4fab-a1bb-30f6656c8880} System.Guid
Preference "Available" string
+ Raw View
I want to use this for a dropdownfor but it doesn't recognise the key and value that I am giving for it:
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"))
Can someone help me with this piece of code? It's possible that there is an easier way of doing this that I am unaware of.
For view
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId,, ViewData["ReturnList"] as SelectList, new { #class = "form-control" })
For Code (Return as viewData)
public SelectList ReturnList(Guid UID) {
var ChairList = Model.Interviewers.Where(d => d.LocKey == Convert.ToString(location.LocationKey) && d.IsChair && d.Date == date.Date).GroupBy(x => new { x.FullDetails, x.InterviewerId, x.Preference }).ToList();
List<SelectListItem> selectItems = ChairList.Select(s => new SelectListItem() {
Text =FullDetails,
Value = InterviewerId.ToString(),
Selected = false
}
).ToList();
selectItems.Insert(0, new SelectListItem() {
Text = " --Select -- ",
Value = null,
Selected = false
});
SelectList selectList = new SelectList(selectItems, "Value", "Text");
return selectList;
}

Html.DropDownListFor will ignore ViewBag values

I have the following action method:-
public ActionResult AdvanceSearch(string AssetTypeName)
{
ViewBag.Techtypes = repository.GetAllTechnologyType().ToList();
ViewBag.AssetID = repository.GetTechnologyTypeID(AssetTypeName);
return View();
}
which will call the folloiwng view :-
//code goes here
#Html.DropDownListFor(model =>model.AssetTypeID, ((IEnumerable<TMS.Models.TechnologyType>)ViewBag.Techtypes).Select(option => new SelectListItem {
Text = (option == null ? "None" :option.Name),
Value = option.AssetTypeID.ToString(),
Selected = (Model != null) && (option.AssetTypeID == ViewBag.AssetID)
}), "All")
//code goes here
but the drop down will always show the default value"All" , instead of selecting the item that match the viewBag value option.AssetTypeID == ViewBag.AssetID. baring in ming that the ViewBag will have the correct value. can anyone adice what might be the problem ?
Thanks
I think your condition is wrong. Try this. Check the 'Selected' property.
#Html.DropDownListFor(model => model.AssetTypeID, ((IEnumerable<TechnologyType>)ViewBag.Techtypes).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Name),
Value = option.AssetTypeID.ToString(),
Selected = (option.AssetTypeID == (int)ViewBag.AssetID)
}), "All")

Dropdowns not rendered when override object.cshtml MVC4

My actual problem was mentioned here.
Hide property of model in dynamic view
To solve the problem, I have overrided object.cshtml as mentioned in the answer.
However, when I did this, the dropdowns that I am rendering using UIHints are not working.
In place of dropdown, just False, False False (the no.of Falses are equal to number of list items I have in my viewdata) are displayed.
I am not sure what is happening here, can somebody advise what is going on?
in my controller:
ViewData["PartyRoleTypeId"] = (IEnumerable<SelectListItem>)PartyRoleTypeRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyRoleTypeId.ToString(), Text = p.Caption, Selected = p.PartyRoleTypeId == obj.PartyRoleTypeId });
ViewData["PartyId"] = (IEnumerable<SelectListItem>)PartyRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyId.ToString(), Text = p.Organization.Caption, Selected = p.PartyId == obj.PartyId });
My dropdown edit template in shared/editortemplates/DropDownList.cshtml
#{
var fieldName = ViewData.ModelMetadata.PropertyName;
}
#Html.DropDownList("",(IEnumerable<SelectListItem>)ViewData[fieldName], "Choose..." , new { #class ="combo"})
object.cshtml
#functions
{
bool ShouldShow (ModelMetadata metadata)
{
return metadata.ShowForEdit
&& metadata.ModelType != typeof(System.Data.EntityState)
&& !metadata.IsComplexType
&& !ViewData.TemplateInfo.Visited(metadata);
}
}
#if (ViewData.TemplateInfo.TemplateDepth > 1)
{
if (Model == null)
{
#ViewData.ModelMetadata.NullDisplayText
}
else
{
#ViewData.ModelMetadata.SimpleDisplayText
}
}
else
{
//ViewData.Clear();
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm)))
{
if (prop.HideSurroundingHtml)
{
#Html.Editor(prop.PropertyName)
}
else if (prop.DisplayName == "Id")
{
<div></div>
}
else if (!string.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
{
<div class="editor-label">#Html.Label(prop.PropertyName)</div>
}
<div class="editor-field">#Html.Editor(prop.PropertyName) #Html.ValidationMessage(prop.PropertyName, "")</div>
}
}
There is some problem with keeping my dropdown values in ViewData or ViewBag.
When I use these, for prartyroletypeid it is not recognizing UIHint dropdownlist.cshtml. It is still referring to object.cshtml.
Instead I kept the dropdown data in TempData and everything is working fine.
But not sure, if I can use TempData in this context.
Any ideas???