I have a structure that looks following
Class TreeNode {
public TreeNode Parent { get; }
public IEnumerable<TreeNode> Children { get; }
public . . . .
}
I want to bind this to a asp.net telerik radgrid with detail tables for each level of the children. I know that radgrid supports declarative binding to a self referencing hierarchy using a datasource control but that assumes you have a flat dataset (e.g. from a database) and can look at a parent key field of some sort. My question has anyone bound a radgrid to a data structure like this before and is there a way to do it declaratively or mostly declaratively?
I can't answer your question directly since I've no experience with the telerik grid, but I can offer a work around.
Add a method to your class that flattens its contents into a self-referencing table like structure such as the one you mentioned. This way you can still work with the class and it's more advanced structure like you want to, but can still output the contents in a consumable form that matches the expectations of the UI components.
This is also a good candidate for an extension method too.
Another possible way I can think of is to build the hierarchy dynamically by filtering the date for the child tables based on their parent inside the DetailTableDataBind grid handler. This demo is a good reference:
http://demos.telerik.com/aspnet-ajax/grid/examples/programming/detailtabledatabind/defaultcs.aspx
but I must agree that Stephen's suggestion might be more handy.
Dick
Related
In trying to make my ASP.Net 4.0 site validate to HTML5 the best I can with the current specification. I have a DataList that always adds cellspacing="0" I've tried different ways of removing the cellspacing="0". I have added a CSS style sheet which does flow over.
Anyone know how to make the DataList conform to the HTML 5 validation?
Actual Code:
Validation Error Message: The cellspacing attribute on the table element is obsolete. Use CSS instead.
Generated Code:
I am not a big fan of DataList - many time, the markup generates is table based and hence semantically incorrect. So I will suggest to use some alternate control such as Repeater or ListView if possible.
Now, if you are in situation where you have plenty of data lists... one of the solution would be to have your own custom DataList control to explicitly override cellspacing attribute such as
public class MyDataList : DataList
{
protected override Style CreateControlStyle()
{
var s = new TableStyle();
s.CellSpacing = -1;
return s;
}
}
You can then probably use ASP.NET Tag Mapping to substitute built-in data-list with your implementation across all pages from config.
In other languages (PHP/Python), I am used to creating a class which represents a given HTML page layout. These classes can have an unlimited number of attributes and dynamic features, such as Navigation (multi level), error messages, info messages, footer text, etc... Most of these items have defaults, but may be overridden on a per-page level. For example:
Layout = MainPage()
Layout.Title = "Google Image Search"
Layout.Nav1.Add("Google", "http://www.google.com", Selected=True)
Layout.Nav1.Add("Yahoo", "http://www.yahoo.com")
Layout.Nav1.Add("Bing", "http://www.bing.com")
Layout.Nav2.Add("Google Image Search", "http://......", Selected=True)
Layout.Nav2.Add("Google Shopping Search", "http://......")
Layout.Nav2.Add("Google Video Search", "http://......")
Layout.Nav2.Add("Google Web Search", "http://......")
or, handling errors:
try:
# do something
except ValidationError as e:
Layout.Error.Add(e)
or a php example:
$Layout->Info[] = "Your changes have been saved!";
My question is: how do I implement similar functionality into ASP.Net MVC 3 Razor (VB)?
So far, I have been able to see how you can use ViewData to pass various bits of data to a view. Also, I have been working with strongly typed views.
Frankly, I'm not sure who's job it is to have this logic, the controller or the view (or is there a model that should be in there somewhere).
Here is a summary of what I am shooting for:
A single place to initialize the default values for the layout (like the first layer of navigation, etc...)
Strongly typed attributes, such as Public Readonly Property Nav1 as List(of NavElement)
And a single place to render these layout elements (I assume _Layout.vbhtml)
Please forgive the here-and-there of this post... I'm trying to figure out the "right way" it's done on a platform that is both new (Razor) and new to me (ASP.Net MVC).
General advise very welcome!
I usually have a controller property (MainMenu) which I add to the ViewData dictionary in Controller.OnResultExecuting in my BaseController. Note that it's named ViewBag in mvc3 and it's a dynamic object.
Another approach would be to use sections in razor. Look at this question: ContentPlaceHolder in Razor?
I lean toward the fat models, skinny controllers perspective. If it were me I would create a base class for your page models that provides support for your common data. You can then inherit from that for individual page models and store your page specific data there.
The MVC implementations that have worked well for me usually have relatively clean Controllers. The controller is just the connector, getting the data from the request into the model and then handing off the prepared model to the correct view.
As for how you store collections of things in .Net - look at the classes that implement IEnumerable interface. Specifically focus on the Dictionary and the List classes. Dictionary objects store name/value pairs and can include nested dictionaries. You can work with them almost exactly like you can use multi-dimensional arrays in PHP. List objects are just indexed collections of items of the same type. You can work with them just like a simple array in PHP.
One side note - if you're just getting started in .Net and coming from a PHP/Python background, it might be better if you can switch to C#. You'll find the syntax much more comfortable and the tutorials/examples more plentiful (especially in the asp.net mvc world)
It's not difficult! :-)
If layout model is of the same type of the content page, the association is automatic! Here is the simplest example...
This is a test layout:
#model string
<style>
.test
{
background:#Model;
}
</style>
<div class="test">
Ciao
</div>
#RenderBody()
And this is a test content page
#{
Layout = "~/Views/Shared/_Test.cshtml";
}
#model string
...blah blah...
Just call the View with something like:
...
return View("Name", (object)"Green");
and it's done! The model is the same in the content page and in the layout page!
Andrea
P.S.: Believe me! This is useful!!! Maybe it's not the best for purists, but it's really useful!!! :-)
I'm working on a website that will allow instructors to report on the academic progress of students in their classes. I've got the website set up two primary pages: one with a user control that displays the classes (a GridView of basic class info with a child GridView in a template field that displays student names and checkboxes to select them -- called MiniStudents), and another with a user control that displays the selected students -- called FullStudents.
Although improbable, it's possible that an instructor could have the same student in two separate classes. I've already accounted for this in the current page setup -- the combination of student ID and class ID (class IDs change each quarter, for those thinking this will be an issue) form a unique key within the database. Recently, one of my users asked if I could break records out by classes on the page, so that instructors would be able easily recognize which class they're operating in.
So, my question is this: is it possible for me to dynamically add a column to the end of the class user control that would allow me to switch out MiniStudents for FullStudents?
If I've left out any important details or if anyone wants/needs code, please let me know.
Try this:
//Under page_load
string path;
if(condition) path = "~/MiniStudents.ascx";
else path = "~/FullStudents.ascx";
Control userControl = this.LoadControl(path);
panel1.Controls.Add(userControl);
And if you have specific properties that you want to set before the usercontrol gets rendered then make them inherit a custom usercontrol class:
public class CustomControl : UserControl
public class MiniStudents : CustomControl
public class FullStudents : CustomControl
So then you can do this:
CustomControl userControl = (CustomControl)this.LoadControl(path);
userControl.UserId = userId;
I hope this helps!
You could add both, and hide one or the other.
You could use a multiview control to control which control is visible. Though I would be concerned about your viewstate size if you are loading all these controls simulantously. It sounds like there could be a lot of data and markup on the page.
I am trying to understand how best to organize some common Dropdown lists used in several views (some are cascading)
Is it best to create
a single \Models\CommonQueries
then create a webservice for each dropdown used in cascading situation
then have a single controller that contains actions for each dropdowns
This way I can follow DRY principle and not repeat the dropdown logics since they are used in various views.
Much Thanks and Regards for reading my question and taking the your time.
+ab
When you say your dropdowns are used in several views, do you still consider these dropdowns as part of the view that is rendering them? If so, I think using a custom HTML helper or a partial view (ascx) is appropriate. Then, like you suggest, you can populate the data for the dropdowns using a common service from your domain layer. I think that is a very reasonable approach.
However, if you feel the dropdowns are somewhat external/unrelated to the view, then you might find that using Html.RenderAction() gives you a much cleaner result. Using Html.RenderAction(), you can output the result of an Action method directly into any other view. Therefore, you can create 1 controller with the necessary Action method(s) to populate those dropdowns. For example, let say you have a view with roughly something like:
<div>
<div id="coreView1">
<!-- some view code here -->
</div>
</div>
<div id="commonDropdowns">
<% Html.RenderAction("Create", "Dropdown"); %>
</div>
where Create is the name of your method in the DropdownController.
For example:
public class DropdownController : Controller
{
public ViewResult Create()
{
// do stuff here to create the ViewResult of the common Dropdowns
}
}
Note: Some people dislike this approach as it doesn't fit the typical MVC seperation of concerns. However, it can be a really great fit for some cases.
Hope one of these approaches can help.
I'm having a right barney getting my head around how everything fits together using the MVVM pattern. It all seems quite simple in practice but trying to implement it I seem to be breaking various other rules that I try to code by.
Just as a side note, I'm trying to implement the pattern using Flex, not Silverlight or WPF, so if anyone can come with good reasons why this shouldn't be done, then I'd like to hear them.
I have a problem where I have several views. Sometimes I have to display two views on the page at the same time; sometimes I switch back to a single view. In my normal Flex brain I would have a main view with a code-behind which contained all my other views (equally with code-behinds). That main view would then do the switching of the other individual views.
When I try to implement this in MVVM I'm trying to stick to the principles of MVVM by using binding which decouples my Views from the ViewModels. Let's say I create a ViewModel for application-wide state and my ApplicationView binds to that data and does all the switching of the sub views.
Now, where should I create my view models for my subviews? I've tried inside the ApplicationView -- that didn't seem right. And then I've tried outside of the application view and passing and instance of it into the ApplicationView and then my sub models a bind to it. Am I missing something? None of these methods seem to fit the whole point of trying to decouple this.
Any good books or links that explain this problem would be much appreciated.
Cheers,
James
The approach you are referring to is ViewModel composition. Its where you have multiple complex view parts that need to bind to their own ViewModel entity. The approach entails constructing a root ViewModel with properties for each child ViewModel. Then the root View is bound to the root View Model and each View (whether displayed or collapsed) is bound to the corresponding property on the root ViewModel.
The ViewModel would look like this:
public class RootViewModel
{
ChildViewModelA ChildA { get; set; }
ChildViewModelB ChildB { get; set; }
}
The View would look like this:
<Grid>
<ChildViewA DataContext="{Binding ChildA}" />
<ChildViewB DataContext="{Binding ChildB}" />
</Grid>
You could also implement this in away to allow yourself to select an active workspace.
The ViewModel would look like this:
public class RootViewModel
{
public List<ViewModel> ChildWorkspaces { get; set; }
public ViewModel ActiveWorkspace { get; set; }
public RootViewModel()
{
ChildWorkspaces.Add(ChildViewModelA);
ChildWorkspaces.Add(ChildViewModelB);
}
}
The View would look like this:
<Grid>
<Grid.Resources>
<DataTemplate DataType="ChildViewModelA">
<ChildViewA />
</DataTemplate>
<DataTemplate DataType="ChildViewModelB">
<ChildViewB />
</DataTemplate>
</Grid.Resources>
<ContentControl Content="{Binding ActiveWorkspace}" />
</Grid>
This will result in the appropriate visual representation being selected implicity based on the type of the actual object stored in ActiveWorkspace.
Pardon my response was in WPF. I tried my hardest to not get caught up in the syntax of it all :-)
As you can see the plurality of "ViewModel" can be ambiguous. Often times we find the need to construct multiple sub-entities to structure the ViewModel appropriately. But all ViewModel entities would be somewhere within the root View Model object.
When implementing MVVM in WPF, I prefer to infer what visual element to apply data context implicitly (as illustrated in the later half of this response). In more complex scenarios I prefer to use a DataTemplateSelector to conduct that decisioning. But in super simple cases you can explicitly apply DataContext either imperatively in C#/ActionScript or declaratively through bindings.
Hope this helps!
I've seen variants of the MVVM approach used on a couple different Flex projects, but I haven't seen an approach that feels perfectly right to me. That said, I think using Presentation Models makes testing in Flex a lot easier, so I'm pretty sure that there will start to be more applications designed around this pattern.
The easiest approach I've seen to implementing MVVM in Flex is to place the individual ViewModels within the application Model / ModelLoactor. The ModelLoactor contains any global data and also serves as an accessor to all ViewModels. ApplicationViews can then bind to their particular ViewModel through the ModelLocator, while ViewModels can be updated both through Commands and through bindings to their parent ModelLocator. One benefit of this approach is that all of the data logic is localized; of course, this could also be seen as a drawback, with the central ModelLocator being a touch brittle due to its hard coded references to all ViewModels.
I've seen cleaner approaches work by using the Mate framework. Mate allows for a much more decentralized injection of ViewModels into the appropriate ApplicationViews. (I suppose this could also be accomplished with Swiz, I'm just not as familiar with that framework). With Mate, each ApplicationView has its ViewModel injected via a Map. What's cool with this approach is how ViewModels can be updated using an EventMap (the Mate version of a FrontController). Essentially, your ApplicationViews will dispatch events that are handled by one or more EventMaps, and these Maps can then make changes to one or more of the ViewModels. This approach allows for a user gesture or event from one ApplicationView to change the state of several ViewModels at once. In addition, because this logic is extracted into Mate's EventMaps, it's very easy to change how events are handled or which ViewModels are changed. Of course, the major drawback of this approach is that you're committing to using Mate as a framework, which may not be an option depending on the requirements of the project.
I hope that helps!
I wanted to share a comparison I wrote up of MVVM (Silverlight) vs PresentionModel (Flex). It shows how the two implementations of the same pattern differ/compare:
http://houseofbilz.com/archives/2010/12/29/cross-training-in-silverlight-flexmvvm-vs-presentation-model/