ASP.NET MVC View information stored in a data-store - asp.net

I'm looking for some advice on storing views in a data-store (database, file, other) and display them based on routing data, all using ASP.NET MVC 2 and ASP.NET Routing.
For example, I'd like to be able to display different views based on the following route data:
/{country}/
/{country}/{area}
But in the same vein I'd like to display:
/{planet}/
/{planet}/{satellite}
All are based on strings, and the data isn't fixed. So based on the number of segments maybe, use that as the selection criteria into the data-store...additionally, I may not know the segments up front, so they'd all be dynamic.
I'm was hoping we could get a few different methods together here, as kind of a reference for all - I'm sure some methods won't suite everyone...
So, how would you do it?
Branislav Abadjimarinov suggested a Controller Factory which could be used to do the look-up and display the page dynamically. I like this idea, what do you think?

There is no way for MVC to understand from this url's which route to choose. You have to make the routes more specific. For example:
/planet/{planet}/{satelite}
/country/{country}/{area}
You also have the option to define your own controller factory. The controller factory decides which controller to instantiate based on the route. So you can put some custom logic in it like - check if the {planet} parameter exist and if yes instantiate Planet controller else instantiate Countries controller.

This Post could be really helpful for you.
Remember you always can add a new routing rule : )
Just like this

Related

Json Dynamic views spring MVC

I am kind of new to spring MVC
and I wanted to use JasonViews (Jackson) for dynamic JSON per request and I didn't want to change my controllers too much .. so #marty here gave me a great solution in his blog
http://martypitt.wordpress.com/2012/11/05/custom-json-views-with-spring-mvc-and-jackson/
The problem is that I need control over the HTTP status codes,so my controllers are returning types of HttpResponse{T} and not List{T} how can I customize the code in order to support parsing of types like HttpResponse{List{Book}}?
If not possible, can I control the Http status code without the HttpResponse?
I may need to see an example of your code to really understand what you are asking, but this might point you in the right direction:
Take #marty's code and try extending HttpEntityMethodProcessor with it.
http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.htmlS
Then, you need to make your method signatures look like
public ResponseEntity<MyType> getMyTypeWithControlOverResponseEntity(...) {...}
You can find more info on this signature type at:
http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-httpentity
Let me know if this is not the right direction you were trying to go or need more help. =)

asp.net MVC3: Trimming all HTTP POST data

I need to do trim to all HTTP POST data submitted by users through web forms. Having done googling, apparently there is no in-built functionality in asp.net to trim all HTTP POST data.
The closest that I can get is what is described here: ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?
Unfortunately it doesn't work on nested ViewModels (ViewModel with property with type of other ViewModel).
What is the best way to achieve this? I don't want to do property.Trim() on every properties in all ViewModel. Thank you.
One option is to define your own IValueProvider. I would start by inheriting from NameValueCollectionValueProvider to make a TrimmedNameValueCollectionValueProvider in which you trim the results as you pull them out. Then you would defined a TrimmedFormValueProvider that passes in controllerContext.HttpContext.Request.Form as the collection.

How can I pass parameters to an Action using Html.Action() in ASP.NET MVC?

I've been using Html.Action("ActionName", "ControllerName") to invoke child actions across controllers without needing to have the view in Views\Shared. This has been working great for displaying things like session or cookie information.
Instead of just accessing cookies, I would like to pass additional parameters to Html.Action("ActionName", "ControllerName") so the action can execute different code based on the the data passed to the original view.
Should I be using a different method to pass parameters to a child action in a different controller? How would one accomplish this?
You could specify additional data in the RouteValues property like this.
Html.Action("ActionName","Controller", new { id = 1 })
To add a little on this question, I am using ASP.Net MVC 5 and I could succeed to achieve this with this code:
#Html.Action("foo",new {parameter1=1})

Fat ASP.NET MVC Controllers

I have been reading about "Fat Controllers" but most of the articles out there focus on pulling the service/repository layer logic out of the controller. However, I have run into a different situation and am wondering if anyone has any ideas for improvement.
I have a controller with too many actions and am wondering how I can break this down into many controllers with fewer actions. All these actions are responsible for inserting/updating/removing objects that all belong to the same aggregate. So I'm not quiet keen in having a seperate controller for each class that belongs to this aggregate...
To give you more details, this controller is used in a tabbed page. Each tab represents a portion of the data for editing and all the domain model objects used here belong to the same aggregate.
Any advice?
Cheers,
Mosh
For all your tabs you can use one action, that have an tab parameter, that indicate what data you need to return.
The controller job is to cast this string tab into enum type variable. Then the tab will be send to the repository, and the repository job is to return data in response to the tab value.
The controller should do its job through to services: Input Validator and Mapper.
The mapper service job is to map the user input (typically strings) into actual typed value (int, System.DateTime, enum types, etc).
The validator job is to check that the input is valid.
Following this principles should keep your controllers really tiny.
If you wanted something simple and easy I'd suggest just splitting up the controller into partial classes based on the tabs. Of course, it's still a fat controller there's just some obvious separation between the various tab functionalities.

ASP.NET MVC routing based on data store values

How would you tackle this problem:
I have data in my data store. Each item has information about:
URL = an arbitrary number of first route segments that will be used with requests
some item type = display will be related to this type (read on)
title = used for example in navigation around my application
etc.
Since each item can have an arbitrary number of segments, I created a custom route, that allows me to handle these kind of requests without using the default route and having a single greedy route parameter.
Item type will actually define in what way should content of a particular item be displayed to the client. I was thinking of creating just as many controllers to not have too much code in a single controller action.
So how would you do this in ASP.NET MVC or what would you suggest would be the most feasible way of doing this?
Edit: A few more details
My items are stored in a database. Since they can have very different types (not inheritable) I thought of creating just as many controllers. But questions arise:
How should I create these controllers on each request since they are related to some dynamic data? I could create my own Controller factory or Route handler or possibly some other extension points as well, but which one would be best?
I want to use MVC basic functionality of using things like Html.ActionLink(action, controller, linkText) or make my own extension like Html.ActionLink(itemType, linkText) to make it even more flexible, so Action link should create correct routes based on Route data (because that's what's going on in the background - it goes through routes top down and see which one returns a resulting URL).
I was thinking of having a configuration of relation between itemType and route values (controller, action, defaults). Defaults setting may be tricky since defaults should be deserialized from a configuration string into an object (that may as well be complex). So I thought of maybe even having a configurable relation between itemType and class type that implements a certain interface like written in the example below.
My routes can be changed (or some new ones added) in the data store. But new types should not be added. Configuration would provide these scenarios, because they would link types with route defaults.
Example:
Interface definition:
public interface IRouteDefaults
{
object GetRouteDefaults();
}
Interface implementation example:
public class DefaultType : IRouteDefaults
{
public object GetRouteDefaults()
{
return new {
controller = "Default",
action = "Show",
itemComplex = new Person {
Name = "John Doe",
IsAdmin = true
}
}
}
Configuration example:
<customRoutes>
<route name="Cars" type="TypeEnum.Car" defaults="MyApp.Routing.Defaults.Car, MyApp.Routing" />
<route name="Fruits" type="TypeEnum.Fruit" defaults="MyApp.Routing.Defaults.Fruit, MyApp.Routing" />
<route name="Shoes" type="TypeEnum.Shoe" defaults="MyApp.Routing.Defaults.Shoe, MyApp.Routing" />
...
<route name="Others" type="TypeEnum.Other" defaults="MyApp.Routing.Defaults.DefaultType, MyApp.Routing" />
</customRoutes>
To address performance hit I can cache my items and work with in-memory data and avoid accessing the database on each request. These items tend to not change too often. I could cache them for like 60 minutes without degrading application experience.
There is no significant performance issue if you define a complex routing dictionary, or just have one generic routing entry and handle all the cases yourself. Code is code
Even if your data types are not inheritable, most likely you have common display patterns. e.g.
List of titles and summary text
item display, with title, image, description
etc
If you can breakdown your site into a finite number of display patterns, then you only need to make those finite controllers and views
You them provide a services layer which is selected by the routing parameter than uses a data transfer object (DTO) pattern to take the case data and move it into the standard data structure for the view
The general concept you mention is not at all uncommon and there are a few things to consider:
The moment I hear about URL routing taking a dependency on data coming from a database, the first thing I think about is performance. One way to alleviate potentialy performance concerns is to use the built in Route class and have a very generic pattern, such as "somethingStatic/{*everythingElse}". This way if the URL doesn't start with "somethingStatic" it will immediately fail to match and routing will continue to the next route. Then you'll get all the interesting data as the catch-all "everythingElse" parameter.
You can then associate this route with a custom route handler that derives from MvcRouteHandler and overrides GetHttpHandler to go to the database, make sense of the "everythingElse" value, and perhaps dynamically determine which controller and action should be used to handle this request. You can get/set the routing values by accessing requestContext.RouteData.Values.
Whether to use one controller and one action or many of one or many of each is a discussion unto itself. The question boils down to how many different types of data do you have? Are they mostly similar (they're all books, but some are hardcover and some are softcover)? Completely different (some are cars, some are books, and some are houses)? The answer to this should be the same answer you'd have if this were a computer programming class and you had to decide from an OOP perspective whether they all have a base class and their own derives types, or whether they could be easily represented by one common type. If they're all different types then I'd recommend different controllers - especially if each requires a distinct set of actions. For example, for a house you might want to see an inspection report. But for a book you might want to preview the first five pages and read a book review. These items have nothing in common: The actions for one would never be used for the other.
The problem described in #3 can also occur in reverse, though: What if you have 1,000 different object types? Do you want 1,000 different controllers? Without having any more information, I'd say for this scenario 1,000 controllers is a bit too much.
Hopefully these thoughts help guide you to the right solution. If you can provide more information about some of the specific scenarios you have (such as what kind of objects these are and what actions can apply to them) then the answer can be refined as well.

Resources