Add ASP.NET MVC Routed URLs to view-model objects (for use in JSON) - ajax

I'm writing an application which uses ASP.NET MVC with JSON.NET as the server, sending JSON to the client which is read by Knockout and then displayed with data-bindings. This is all working wonderfully, except for one problem:
I have a class Customer which is used to generate a ReviewAuthorViewModel class - the latter is meant specifically for JSON serialization and removes unnecessary fields, circular references, etc. On the client, I want to render a link to the Customer's profile page, with the URL coming from a defined MVC route "user/{username}". Because I'm sending this via JSON, I don't have a .cshtml page in which I can call Url.Action.
The question is: For an arbitrary object, how do I most efficiently/elegantly get a URL for an action with some data, without a .cshtml view?
I'd prefer a solution that doesn't require extra code in each action, but that may be the only choice apart from recreating the routing tables client-side in JavaScript. Below are the things I've already tried, and what was unsatisfactory with each.
Solution Attempt 1
Call the UrlHelper.Action method in the ReviewAuthorViewModel class. However, the UrlHelper requires a request context. For the sake of separation of concerns, I don't want my view model to have a dependency on System.Web.Routing, nor do I want it to need a request context to function.
Solution Attempt 2
Create a class RouteInformation with members Controller, Action, and Data, and an interface IUrlViewModel with two properties, a get of type RouteInformation and a get/set string named Url. The view models needing links then implement this interface, and controllers look for view models of type IUrlViewModel and run UrlHelper.Action with the information from the view model's RouteInformation instance, storing the result in the Url property.
This one works but without reflection I don't know how to find view models implementing IUrlViewModel within other view models, and it feels very kludgy.

Solution Attempt 1 is the OK solution. In asp.net-mvc, view models are part of presentation layer, designed specifically for use with views. You should not worry about having view model depend on asp.net specific things. In fact, they should be coupled, as they should be designed to maximize simplicity of view generation and data exchange between web server and web client. And it's good solution to create separate view model and not use Customer class directly for clients. It wouldn't have been OK if Customer was dependent on Routing.
In fact, you could set that property in controller -
[HttpGet]
public ActionResult Get()
{
var viewModel = new ReviewAuthorViewModel();
viewModel.ProfilePageUrl = Url.Action("Index", "Profile");
// return viewModel;
}

Related

In a "classical" web MVC, how is the view created?

In a "classical" web MVC - please correct me if I'm wrong:
the controller passes the request data received from the "user" (be it browser, console, etc) to the model layer (consisting of domain objects, mappers, repositories, services, etc),
the model layer processes it and returns some result data,
the view - as specialized class(es) - processes the result data and sends/displays it to the "user".
I would like to ask:
Does the controller create the view?
Or does the controller receive the view as a dependency?
Or are the controller and the view created completely separately, on the front controller level (let's say in index.php)?
Thank you.
Your definitions of MVC in generally is right, here is answer for your ask:
Controllers are not responsible for rendering the interface, nor for
presentation logic. Controllers do not display anything. Instead, each
controller's method deals with different user's request. It extracts
the data from said request and passes it to model layer and the
associated view.
Decisions about what and how to display are in purview of views. Views
contain the presentation logic in MVC pattern. In the context of web
applications, views create the response. They can compose a from from
multiple templates or just send a single HTTP header.
Controllers can signal the associated view by passing some specific
values of the request to that view, but most of the decisions in the
view are based on information that the view requested from different
services in the model layer.
A Controller's methods are based on what type of requests a user can
send. For example in a authentication form it might be: GET /login
and/or POST /login.
Source: Controllers, tereško
Classic correct MVC class structure:
Easy definition:
Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
View. The view manages the display of information.
Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.
Source: Microsoft Docs
Additional resourses: (only useful ones)
External
MVC Explanatory [computer science design patterns]
Creating a Custom Controller and View in CodeIgniter [a visual example]
Codeproject's definitions MVC: easy | extended
Internal
The relationship between Model, View and Controller
MVS in a conversation form
The controllers are entry point of MVC, controllers call to model , and model check wich view display , example, magento (mvc)

Asp.net mvc Data Model or View Model

I am very new to asp.net mvc techniques, and have a question about how to render a view. In my project, I need to retrieve an XML file(XML string) from database. After getting this XML string, I deserialize xml to an object, say LogMessage, which I have defined already. Once I have got such a LogMessage object, I would like to display its contents to the user via a view. Additionally, I need to process some of the LogMessage properties before showing them to the user. For instance, (1) there is a logTime property in the LogMessage object, which is in utc format and I need to convert it to the local time, (2) there is a logCode property, which is in the format of int number (1,2,3, etc), and I need to convert each number to a meaningful name, such as eventStart, eventEnd, etc.
What in my mind now is that I create a strongly-typed view (of LogMessage type) in asp.net mvc3, so that I can render the view with Razor. Also I put all the necessary functions (e.g., for converting utc time to local time, mapping code number to its meaningful name, etc.) in the same view file, and call them when rendering the view.
But I am not sure whether I should do it as the aforementioned way or I should create another view model, say LogMessageViewModel (as I think actually the LogMessage is my data model or not ?). Then once I have got the LogMessage object, I can create a LogMessageViewModel (and LogMesageViewModel looks quite the same as LogMessage), and initialize the LogMessageViewModel with LogMessage and do all the necessary conversions in my Controller or Model, rather than do them in the View. Then now I have all the correct information in the LogMessageViewModel for the view, and create a strongly-typed view of LogMessageViewModel and simply render a view and show its contents to the user.
Could anyone give me some suggestions about these two different approaches or maybe there are some other better ones?
It is always a good practice to keep the DB layer and the UI layer seperate.
When you are getting data from the DB and storing it in a DataContract(LogMessage in your case), Use automappers to map it to a similar viewmodel(LogMessageViewModel ). Then use the viewModel in the views.
the flow goes like this
DB-> XML values -> LogMessage(DataContract/ Domain Object)-> using
AutoMapper -> LogMessageViewModel-> View
A Razor view engine that is used to render a Web Forms page to the response
Please go to here : ASP.NET MVC View Engine Comparison
That link may help your questions
and refer to : Rendering ASP.NET MVC Razor Views
It is always recommened to use ViewModels , if you require any more information that needs to rendered apart from the information from the model
If any additional processing needs to be done, you can do it in your view model.
Then, you can create a view strongly typed with the view model.
Hopw this helps..
If you are not using models, all the transformation logics , additional data needs to sent to view by using view data.
This makes controller fat.
It is a best practice to maintain your controllers as thin as possible.
Since, considering Single responsibilty principle . The responsibity of controllers is only to make transfer of controls.not any other thing else
**Conclusion: *Recommened to use ViewModel in your scenario***
Hope this helps..

MVC, controller - use cases

I've learned that you should set up the controller-class in a MVC-OOD as a use case, from top to bottom in only one method that run the MVC-classes.
Is it OK to use different methods in one controller to get more control and better overview?
Let's say you wanna run a controller that will display a login form (getting the html etc from the View). And the same controller will also display a log-out button IF the user is NOT logged in.
This could be done with a single method in the controller, but using two methods seems better. One method to call if you want the login form, and one to call if you want to log-out button.
(just an example)
So, what does the pros say. Should each controller contain one "use case" method only, or could it be several?
TL;DR -- you have misunderstood the MVC design pattern and are doing it wrong.
Controllers are not responsible for rendering the interface, nor for presentation logic. Controllers do not display anything. Instead, each controller's method deals with different user's request. It extracts the data from said request and passes it to model layer and the associated view.
Decisions about what and how to display are in purview of views. Views contain the presentation logic in MVC pattern. In the context of web applications, views create the response. They can compose a from from multiple templates or just send a single HTTP header.
Controllers can signal the associated view by passing some specific values of the request to that view, but most of the decisions in the view are based on information that the view requested from different services in the model layer.
A Controller's methods are based on what type of requests a user can send. For example in a authentication form it might be: GET /login and/or POST /login.
Its important to remember two things with MVC, firstly, its an Object-Oriented Architecture, and secondly, It should be used for separating concerns.
Separation of Concerns is related to Abstraction, It is to aid us in understanding the section of code at hand. The Model and View are both collections/domains of related objects. Each object is fully complete and relevant to its domain.
You will find objects with types such as Buttons, Images, Text Inputs etc inside your View, and you will find business related objects (User, Account, Profile etc) within your Model.
The collection of objects inside your Model don't tend to do much, They require logic to wire the objects together. (Or simply delegate simple single object requests to the correct object)
The Controller provides the interface into your Model, and contains the business logic related to the Model and the interactions between the Model objects. You will have a single Controller for your Model, and the Controller will have multiple methods which will align with your use-cases.

Defining models on server side when using MVVM with Knockout.js

I am planning to use knockout.js and MVVM pattern on the client side for a Single Page application. So Models, ViewModels would be defined on the client side. I am confused about how we have to structure on the server side.
Now, would controllers just return domain model itself ? Would all the mapping from domain model to ViewModel happen only on the client side ?
In my solution, there is wide gap between the Domain model and the ViewModel. So the above approach would result in a lot of data being returned to client side unnecessarily. Though it seems like overkill, I am thinking about repeating ViewModel and InputViewModel definitions (former represents data rendered, latter represents data to be posted back to controller actions) on server side and also having a mapping layer (based on automapper) to map Domain models to ViewModels on the server side. Does this make sense ? Or is there a better approach ?
I would suggest that you work out what data your view models actually need, then have the controllers build up a server-side view model that contains that data and send it to the client in a JSON format.
This way you are not sending unnecessary data over to the client (or back), you are still able to do much of the heavy lifting on the server and the knockout view models can do what they are meant for: presenting the data to be used by the view.
What you described in point 2 is actually the solution I use the most and it makes sense to me:
I use Automapper on the server side to map between Domain models and ViewModels (.Net objects) that are View specific and contain only the data the View needs.
The Controller Action that is responsible for loading the View the first time, will databind the View to the ViewModel, so that the page is initialized quickly without the need to make an Ajax call.
In the View itself I create the knockout viewmodel, assigning any initial values (if needed) by Json encoding the bounded ViewModel (for example using Asp.Net MVC i would do something like
var boundedViewModel = #Html.Raw(Json.Encode(Model));
That is exactly how I would approach this problem. If this were a straight MVC app, you would still be creating viewmodels.
Sometimes for complicated data sets, I can see a use case for using something like Knockback, which takes the rich data model of backbone.js and combines it with knockout.js
http://kmalakoff.github.com/knockback/

ASP.NET MVC: Where do you assemble the view model for a view?

From inside to outside, these are our MVC app layers:
MS SQL / Tables / Views / Stored Procs
Entity Framework 4.1 (ORM) with POCO generation
Repository
Service (retrieve) and Control Functions (Save)
Routing -> Controller -> Razor View
(client) JQuery Ajax with Knockout.js (MVVM)
Everything is fine until I need to create a single ViewModel for step 5 to feed both the Razor view as well as the JSON/Knockout ViewModel:
Header that includes all Drop down list options and choices for the fields below
Items - an array of whatever we send to the client that becomes the ViewModel
Since the Controller won't have access to the Repository directly, does this mean I create a service for each and every view that allows editing content? I'll need to get the POCO from the repository plus all options for each field type as needed.
It just seems redundant to create separate services for each view. For example, a viewModel to edit an address and a separate viewModel to edit a real estate property that also has an address. We could have a dozen forms that edit the same address POCO.
To make this question easier to answer, is allowing the Controller direct access to the repositories a leaky abstraction?
Well, so are your controllers going to have code that translates POCOs from Entity Framework into separate view model objects?
If so, then you should move that code to a separate class, and follow the single-responsibility principle. Whether that class is in the "service layer" or not is up to you. And whether you use AutoMapper or not is up to you. But these kind of data mappers should not be part of the controller logic; controllers should be as dumb as possible.
OK, now let's ignore the data mapping problem, and pretend you could always use your POCOs directly as view models. Then you would still want a service layer, because it would translate between
userService.GetByUserName("bob")
in your dumb controller, and implement that in a specific manner by returning
userRepository.Users.Single(u => u.UserName == "bob")
Putting these together, your UserController ends up taking in IUserService and IUserDataMapper dependencies, and the code is super-dumb, as desired:
public ActionResult ShowUserPage(string userName)
{
var user = userService.GetByUserName(userName);
var viewModel = userDataMapper.MakeViewModel(user);
return View(viewModel);
}
You can now test the controller with stubs for both dependencies, or stub out IUserDataMapper while you mock IUserService, or vice-versa. Your controller has very little logic, and has only one axis of change. The same can be said for the user data-mapper class and the user service class.
I was reading an article this morning that you might find somewhat illuminating on these architectural matters. It is, somewhat condescendingly, titled "Software Development Fundamentals, Part 2: Layered Architecture." You probably won't be able to switch from a database application model to the persistent-ignorant model the article describes and suggests. But it might point you in the right direction.
i personally always inject the repository/repositories into the controller. i'm not sure why you would want to have a service layer between the repository and the controller. if anything you would use specifications.
once you've done that, check out automapper. its a mapper that, once properly configured, can map your domain model to your viewmodel, and back again.

Resources