loop to find parent id [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Is it possible in C# to carry out a loop to find the parent id for a particular page?
Here's the scenario: I'm developing a breadcrumb. For each page I need the parent Id, so I can use that to populate a list with a url and a page title.
1st page --- Parent page --- Grandparent page
I need to be able to do a loop to gather the parent id, then that will populate the list which goes through and finds the new parent page parent id (basically for the grandparent page) and then populates the list until there aren't any more.
At the moment the current page data is stored in var pageInSiteMap:
var overview = new List<PageDataModel>();
pageInSiteMap // A get command is used to place the data in here
if(pageInSiteMap != null && pageInSiteMap.ParentId.HasValue)
{
var parent = allpages.Data.Items.FirstOrDefault(x => x.Id == pageInSiteMap.ParentId
var parentEntry = new PageDataModel{
pageUrl = parent.Url, pageTitle = parent.Title
};
overview.Add(parentEntry);
}

I am going to take a stab at this and assume you need recursion, here is a quick example I wrote:
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public Page Parent { get; set; }
}
public class Class1
{
public List<Page> GetPages(Page currentPage)
{
var ret = new List<Page> {currentPage};
if(currentPage.Parent != null)
ret.AddRange(GetPages(currentPage.Parent));
return ret;
}
}

Related

C# how does this code work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Public class form1
{
List<Data> dataInfo = new List<Data>();
private void UpdateBinding()
{
supplierBox.DataSource = dataInfo;
supplierBox.DisplayMember = "Supplier";
}
}
I have another class called Data:
public class Data
{
public string Supplier { get; set; }
}
This is able to update my textBox named supplier on Visual Studio with data from my SQL Server that I have grabbed. How would I access the data from my SQL Server if I just wanted to put it in a variable like var?
supplier.Text = dataInfo.FirstOrDefault().Supplier;
would place the first element from your list of suppliers into your text box named "suppliers". If you don't have any items in your list of dataInfo then you would get a NullReferenceException.

List that contains list that contains list and so on in c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is code:
public class Comment
{
public DateTime CreateAt { get; set; }
public Comment ParentComment { get; set;}
public List<Comment> SubComments { get; set; }
public string Text { get; set; }
}
I'am trying to do something like on facebook. You can comment every single comment, so there will be like a tree of comments.. I'am having trouble with trying to display all the comments, precisely text. I can't figure out how to do that. If anyone could help I'll appreciate it!
You can use recursion for process each comment and their sub comments for example:
public void checkComment(Comment comment)
{
//Check if the comment is valid
if (comment != null)
{
//Do whatever you want to do with your comment for example print to console
Console.WriteLine(String.Format("Comment: {0}", comment.Text));
//Check if i have any sub comments
if (comment.SubComments.Count > 0)
{
//Process each sub comment (recursive)
comment.SubComments.ForEach(x => checkComment(x));
}
}
}

How to link a dropdownlist and table data to change data on selected item on same id? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
When I select an item in a dropdownlist, I want my table to refresh data on same id. As you can see, I want my table 1 in a dropdownlist and table 2 in a table-like grid
So when I pick from table 1 id 1, my grid will refresh data on foreign key 1, and when I pick from table 1 id 2, my grid will refresh data on foreign key 2, etc.
Update: This is a fairly common problem that all new developers to MVC will encounter. I have updated my answer to include a complete working example on how to solve this. I suspect it will help other new comers in the future..
You will need to accomplish this with some JavaScript (JQuery) and another action on a controller that will return your list of related items based on the id selected OR you could have the child action return a partial view with the select list data.
Your first task is to wire up an event in script to the .change() event on your first drop down list.
Once you have that captured - you can post the id to other action and have it return your data or partial view.
Solution
Cascading drop downs in MVC are accomplished through a combination of a few techniques. You need view models to render the drop downs (select lists) and you will need some JavaScript code to capture events on the client browser and get additional data. Finally you will use a partial view to return back to the client.
In this example - we are going to create a Select List with 3 parent values in it. When a user selects a different value, we will request a new second drop down list corresponding to the parent values.
I created simple model classes
public class Catalog
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CatalogDate { get; set; }
}
public class Book
{
public int BookId { get; set; }
public int CatalogId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class CatalogViewModel
{
public int SelectedCatalog { get; set; }
public List<Catalog> Catalogs { get; set; }
}
public class BookViewModel
{
public int SelectedBook { get; set; }
public List<Book> Books { get; set; }
}
The catalog and book view models will be used in our Razor views with an DropDownListFor HTML helper. The SelectedCatalog and SelectedBook properties hold the actual selected value - while the Catalogs and Books properties are used to load the Select Lists.
On the Index action of the Home controller - I modified the method:
public ActionResult Index()
{
CatalogViewModel model = new CatalogViewModel()
{
Catalogs = Catalogs(),
};
return View(model);
}
Here will will return a list of catalogs in the CatalogViewModel.
I also added in a another action that we will use for the Ajax call:
public ActionResult Books(string catalogId)
{
int catId = Convert.ToInt32(catalogId);
var model = new BookViewModel()
{
Books = Books().Where(x => x.CatalogId == catId).ToList()
};
return PartialView("Partials/_BooksDropDownList", model);
}
This method will accept the catalog Id specified by the user and retrieve a list of books corresponding the catalog id. This will then be used in a partial view and returned to the caller.
The Index view of the Home controller:
#model WebApplication1.Controllers.HomeController.CatalogViewModel
#Html.DropDownListFor(m => m.SelectedCatalog, new SelectList(Model.Catalogs, "Id", "Name"))
<div id="bookContainer"></div>
<script>
$(document).ready(function () {
$('#SelectedCatalog').change(function () {
CatalogChanged();
});
});
function CatalogChanged() {
var catalogId = $('#SelectedCatalog').val();
$.get('#Url.Action("Books","Home")' + "?catalogId=" + catalogId,
function (data) {
$('#bookContainer').html(data);
});
}
Here we have the model defined, an Html helper that renders our first Drop Down List, an empty containing div to hold the second drop down list and some script.
The script is simply capturing the .change event of the drop down list and calling the CatalogChanged function. In this function, we get the value of the drop down list and issue a get request using a Url helper to construct the url back to the Home/books action.
Here is the partial view loaded dynamically based on the selected value from the first drop down.
#model WebApplication1.Controllers.HomeController.BookViewModel
<div id="BookDropDown">
#Html.DropDownListFor(x => Model.SelectedBook, new SelectList(Model.Books, "BookId", "Name"))
</div>
That's it. This is a fairly common way of solving this type of problem. There are other ways (like using data and generating the html from script).
I wrote this out because it can be overwhelming getting started and hopefully this will help someone else out down the road.

How to select two set from collection in linq [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a collection defined by:
public class CompanyModel
{
public int compnSN { get; set; }
public string compnName { get; set; }
public string compnAddress { get; set; }
}
How can I get out two set compnName and compnAddress together so that I can use each of that pair value one by one in a foreach loop ?
I tried:
var pairs = from companies
select new {name = companies.compnName, addr = companies.compnAddress}
foreach (var item in pairs)
{
//do some things with item.name;
//do some things with item.addr;
}
I know this idea can be executed but is my grammar wrong somewhere?
Try this one:
var result = companies.Select(x => new
{
Name = x.compnName,
Address = x.compnAddress
});
or this one:
var result = from company in companies
select new
{
Name = x.compnName,
Address = x.compnAddress
};
Then as you already pointed out:
foreach(var company in result)
{
// access the name like company.Name and do what you want.
// access the address like company.Address and do what you want.
}
UPDATE
The code you have posted has some grammatical errors. So despite the fact that your logic is correct, this piece of code will not be compiled.
Specifically, in the following piece of code:
var pairs = from companies
select new {name = companies.compnName, addr = companies.compnAddress}
you try to declare a local variable called companies that should belong in a collection.
Hence we should write this like below:
var pairs = from item in items
Now item is a local variable that refers to the random element in the collections called items. Then as you already have writen you will declare an anonymous type in the select clause:
var pairs = from item in items
select new
{
PropertyA = item.PropertyA
PropertyB = item.PropertyB
};

get model from List of a model [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a way to get the specific items from the list of a model without using a foreach of the list? like if you return a List<model> holding a model with a few differnt items to specifically call those item.
If you want a list of a specific item that's within your list then you can use LINQ to return those items, for example:
var customerNames = customersList.Select(customer => customer.Name);
This would give you a string collection with all of your customer names equal to the amount that was in your original list.
Or if you would like to retrieve a number of different items from your model list then you may want to look into creating a class specifically for stripping out those items, for example:
public class CustomerContactDetails
{
public string Address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
...
var contactDetails = customersList.Select(customer => new CustomerContactDetails { Address = customer.Address, Email = customer.Email, Telephone = customer.Telephone });
You can use C# LambdaExpression, like this:
var yourModel = modelList.Where(x => x.Id = 12).Select(x).First();

Categories

Resources