how to build html navigation bar dynamically using data from database - c#

I have this data from database with self relation
Parent_ID Name Child_ID
1 cities null
2 Egypt 1
3 Saudi 1
4 technology null
5 vb.net 4
6 c# 4
Now i want to build html navigation bar using this data
To be like the following
<ul>
<li>cities
<ul>
<li>Egypt</li>
<li>Saudi</li>
</ul>
</li>
<li>technology
<ul>
<li>vb.net</li>
<li>c#</li>
</ul>
</li>
</ul>
I don't know what is the best way to da that
My be xml node or my be using linqu ...
Whatever the best way help me please.

you can use asp:reapeater control provide datasource to it and give html format inside it. The easiest and the efficient way.
Explore it more....
Edited: You must mention
in mvc, you can pass data inside viewBag, viewdata whatever you like and on view you can use foreach iteration and inside it generate the required html
like
ViewDate["data whatever"] = your data
and on html
#foreach(var item in ....)
{
<a href='item.whatever Value'>
}

OK, here is one method of creating a n deep menu viewmodel
grab all the data from the table with one select and populate a list of menuItemMVs. create a menuMV object and put this list in the static AllMenuItems list. create a razor view for the root of the menu and bind it to menuMV. create a partial view for a menu item which binds to menuItemVM this should contain a for loop looping through the childern and recursively calling RenderParital itself (the partial view) for each child in the menuItemVM it is rendering.
get your root menu razor to loop over the rootMenuItems and renderpartial your menuitem partial view for each
public class menuVM
{
public static List<menuItemVM> AllMenuItems { get; set; }
public IEnumerable<menuItemVM> rootMenuitems
{
get { return menuVM.AllMenuItems.Where(c => c.ParentId == null); }
}
}
public class menuItemVM
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get;set; }
public IEnumerable<menuItemVM> Childern {
get
{
return menuVM.Childern.Where(c => c.ParentId == this.Id);
}
}
}
ps. I think you have childId and parentId the wrong way around in your
sample data

Related

Handling CheckboxField in GlassMapper

I am currently using Glass Mapper to map items in the sitecore tree to Model classes in C#, however I am having issues when trying to read the Checked parameter of a checkbox field on the item.
How do I read the Checked property? I have tried setting the field below to a CheckboxField data type but it has still failed to load the data I require.
Will I need to create another Model class to extract the CheckboxField template data values?
The class property definition
[SitecoreField("Is Gold Class Package")]
public virtual CheckboxField IsGoldClassPackage { get; set; }
The Razor markup
#foreach (var package in Model.LoyaltyPackages.LoyaltyPackageDataItems)
{
<div vrewards-item title="#package.Title" unlocked price="#package.Points" icon="#package.Icon"
#(package.IsGoldClassPackage.Checked == true ? goldClassAttrribute : "") >
</div>
}
In Glass you don't map the fields but just the values. So your domain model should look like this:
[SitecoreField("Is Gold Class Package")]
public virtual bool IsGoldClassPackage { get; set; }
And in your view you can simply get the value from the model:
#foreach (var package in Model.LoyaltyPackages.LoyaltyPackageDataItems)
{
<div vrewards-item title="#package.Title" unlocked price="#package.Points" icon="#package.Icon"
#(package.IsGoldClassPackage == true ? goldClassAttrribute : "") >
</div>
}

Pre-processing Form data before Model validation in MVC

I am fairly new to MVC, but have quite a bit of experience in development in general, and am having an issue with MVC request life cycle it seems.
Will try to keep this simple, even tho the project is a bit complex in some areas.
I have a view bound to a view model that has a few complex list properties. These properties are displayed via checkboxes who's IDs are not directly related to any property in the model, but instead related to the IDs of the objects in the List<>. Because of this, the checked values do not automatically get applied to the model on POST.
To get around that, I added code in the Action method in the controller that parses the proper controls (in the Request.Form collection) and assigns the checked/selected value to the proper list items in the model.
This works perfectly up to a point.
Now, I also use Fluent Validation, and the problem is when performing custom validation rules when posting a new model to the server. The Validation routine is firing BEFORE the controller's action method, and thus before my processing of the list objects.
So, my question is, is there a way I can override the initial call to the model validation so I can just call the validation manually after my processing? I know I can do that which will fix the problem without overriding the initial call, but some of the validation takes a bit of time to process since it requires linq queries to a live database, so I do not want the validation to fire 2 times - that will quite literally double the time it takes to return no matter if the model is valid or not.
EDIT: Adding a example:
namespace Models
{
[Validator(typeof(MemberValidator))]
public class ViewMember
{
public int MemberID { get; set; }
public short RegionID { get; set; }
public List<PropTypeInfo> PropTypes { get; set; }
}
}
PropTypeInfo class:
public class PropTypeInfo
{
public byte ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Selected { get; set; }
public PropTypeInfo(byte i, string n, string d, bool sel)
{
ID = i;
Name = n;
Description = d;
Selected = sel;
}
public static List<PropTypeInfo> GetAll(bool selected = false)
{
List<PropTypeInfo> output = new List<PropTypeInfo>();
OpenAccess.Context context = new OpenAccess.Context();
var list = (from f in context.Prop_Types orderby f.PropType select f).ToList();
foreach (OpenAccess.WebrentzServerPayments.Models.Prop_Type p in list)
output.Add(new PropTypeInfo(p.PropType, p.PropName, p.DisplayText, selected));
return output;
}
}
now here is the code in the view that renders the checkboxes for each item in the list:
<div class="Column Emp-PropTypes">
#foreach (WebrentzServerPayments.Models.PropTypeInfo ptype in Model.PropTypes)
{
<div style="float:right;width:20%;font-weight:bold;">
#Html.CheckBox("ptype_" + ptype.ID, ptype.Selected, new {Value=ptype.ID}) #Html.Raw(" ") #ptype.Name
</div>
}
</div>
And here is the code I use in the Controller Action method to pull that data back in to the List:
foreach (PropTypeInfo info in member.PropTypes)
info.Selected = form[string.Format("ptype_{0}", info.ID)].Contains(info.ID.ToString());
As a little background, a "PropType" is a type of property (house, condo, apartment) - there are about 2 dozen of them, and more can be added/removed at any time. The list in the class called "PropTypes" is first populated with the Name, Description and ID from a table in the database that lists all the available proptypes for that region.
We then will mark the proptypes as "selected" if the user has chosen that particular type. Those are saved to a table called Member.PropTypes (MemberID, ProptypeID).
So, at runtime the list will contain one record for each available proptype and the selected property will be set to yes if that user has selected it. That makes it easy to render the full list in the view...
Its actually quite a bit more complex as there are almost a dozen such lists, but each works the exact same way just with different data, as well as about 200 additional properties that are easier to manage. Only these lists are causing the issue.
Any help appreciated!
Dave

Convert model to list before passing it to view

I got this model in my project:
public class ListOfProducts
{
public List<string> ProductNames { get; set; }
public List<string> ProductUrls { get; set; }
}
The way I pass it to my view is:
public ActionResult Index()
{
var listOfUrls = GetListOfHrefs(); //Methods for giving values
var listOfProductNames = GetListOfProductNames();//Methods for giving values
var model = new ListOfProducts {ProductUrls = listOfUrls, ProductNames = listOfProductNames, ProductGtin = listofGti};
return View(model);
}
I would like to pass my model to the view as a list in order to loop through it the way i Want...Can I convert my model to a list before passing it?
Tried model.Tolist() but the intellisense could no find the Tolist-Part
EDIT:
I really need to acess both properties in the same context..In this case the Artice
<article id="post-62" class="post-62 x-portfolio type-x-portfolio status-publish has-post-thumbnail hentry has-post-thumbnail x-portfolio-5e9a5c5e0b6c2e1342bfccc9cacb084f x-portfolio-3ce959340d6fed7ed4f041884b46387c">
<div class="entry-wrap cf">
<header class="entry-header">
<h2 class="entry-title entry-title-portfolio">
<p>#product</p>
</h2>
</header>
</div>
<p>#url</p>
<span class="visually-hidden"><span class="author vcard"><span class="fn">addiadmin</span></span><span class="entry-title">Gluten & Mjölkfri Raggmunk</span><time class="entry-date updated" datetime="2014-05-21T08:23:32+00:00">05.21.2014</time></span>
</article>
its the same to ask "I wanna send MyClass as list ...", this is a basic OOB(Object-oriented programming) concept question IMO..so send List{MyClass} , you are sending one object name ListOfProducts which contains 2 lists, do you mean List{ListOfProducts} ? you can attach any Model , any parameters to the View as you want to them , modify it(any Model /ViewBag.Something) to your needs as you please , you are the game ruler
return View(new List<ListOfProducts >{model});
ListOfProducts is an object with properties that are lists.
I think what you are wanting is
#model ListOfProducts
foreach (var item in Model.ProductNames)
{
....
foreach (var item in Model.ProductUrls )
{
....
EDIT: Following on from your comments, you could do this (but see comments at end)
#for (int i = 0; i < Model.ProductNames.Count; i++)
{
<article id="post-62"...
<div class="entry-...
<header class="entry...
<h2 class="entry-title...
<p>Model.ProductNames[i]</p>
</h2>
</header>
</div>
<p>Model.ProductUrls[i]</p>
....
</article>
}
but this will only work if both ProductNames and ProductUrls contain exactly the same number of elements, in which case perhaps you should re-think your model
public class Product
{
public string Name {get; set;}
public string Url {get; set;}
}
Then create a List<Product> in you `Index' action method and pass that to the view
You cannot currently convert ListOfProducts to a list as it's has nothing to do with a list. It's a new type which you have defined in your code.
if you want it to be a list, you should inherit from IEnumerable for example or ICollection and implement the required functions.
Actually, to implement IEnumerable, you need a property in ListOfProducts that will contain all your List<String> so you could iterate on that !
If I assume that each entry in the list ProductNames matches one entry in ProductUrls, then what your really after is a list of Products and the design is missing the 'Product' class.
Create a class like:
public class Product
{
public string Name {get;set;}
public string Url {get; set;}
}
Now replace your 'ListOfProducts' with:
List<Product>()
Now you have a list of products. Your class ListOfProducts is not required.

How to use teleric treeview control in asp.net mvc framework?

I want to use telerik treeview in mvc, but i don't want to use kendo UI, and i can't fine any example of teleric treeview for mvc.
can any one help me or give me any example so i can learn and understand?
I want to use treeview with checkbox and list is like this...
{
pencil
*natraj
*apsara
pen
*bollpen
>rotomak
>add jel
*Inkpen
Eraser
*natraj
}
This type of list then how can i use teleriK treeview with mvc framework for insert and delete function?
it's relly need please give any example or sample code.
Sample code:
#model YourModelTree
#(Html.Telerik().TreeView()
.Name("TelerikTree")
.ShowCheckBox(true)
.BindTo(Model, mappings =>
{
mappings.For<YourModelTree>
(binding => binding
.ItemDataBound((item, modelItem) =>
{
item.Text = modelItem.Name;
item.Value = modelItem.Id.ToString();
item.Expanded = true;
item.Checked = true;
}).Children(c => c.Children));
})))
Example of model Tree:
public class ModelTree
{
public int Id { get; set; }
public string Name { get; set; }
public IList<ModelTree>() Children {get;set;}
public ModelTree Parent {get;set;}
}
Also you can check telerik documentation .If you have any question please ask me.

How to Convert an IEnumerable model object to single model object in view , MVC3

This is not a duplicate.Though the other question is same as this it got solved when it deviated from the procedure. Here i again stumbled upon the same question.
Iam using a DB First approach.
I have a context file called Dynaportal.context.cs, which has the class called DynaPortalEntities:-
public partial class DynaPortalEntities : DbContext
{
...
public DbSet<Page> Pages{ get; set; }
public DbSet<TemplateMaster> TemplateMasters { get; set; }
}
In view
#model DynaPortalMVC.Models.DynaPortalEntities
and in a foreach loop
#foreach (var item in Model.TemplateMasters)
{}
In the same view , I need a page model which is not iEnumerable, like this:-
#Html.EditorFor(model => model.Pages.Title)===========>This shows error under Title
So here i should convert the IEnumerable Model.Pages to a single page object to get model.pages.Title.
Yes, if I understand correctly, Razor does not know what Page you want the title for since you are asking for the Title of all Pages.
Usually, you would loop through the Pages and output each title using #foreach. Or, index into the Pages: #Html.EditorFor(model => model.Pages.First().Title).

Categories