MVC Razor View Code Execution - c#

I am working on my first ASP.Net MVC Application . I am using Razor view and MVC version is 3.
I am getting data for my model from the database in some raw format. Then i do some processing on it like concating strings, format date columns using some linq queries. Everything on the data that i already have in the model class.
I wonder all this code execution is happening on server. I want to move this burden from my server to client machines, i want to pass this raw data to my view and then write code in view to do this loop things and formatting etc.
I just want to confirm if this is a good approach to move on and if this really release some burden from my server.
Thanks

C# or VB that is written in your view is not client side. It's still server side. It's used to manipulate the rendering of the HTML before being passed to the client.
You'd have to pass all your raw data then process it with JavaScript.
Performance of your app would depend on each client machine and therefore not be consistent between 2 users. Maintenance would be tricky as a result.
To cut a long story short I would not recommend it. Your server is most likely designed to handle load. It's the right place for this sort of thing.
And I'd also read up on server / client side code execution relations. Simply doing MVC is a good start. It naturally teaches you how the web works more so than using web forms.

This may be pre-mature optimization. I doubt whether a server would be bogged down performing simple things like string concatenation, formatting, etc.
I suggest you only focus on this if you run into performance issues; else it isn't worth the effort.

I think you confused a View in MVC with browser HTML. You can have any C# code in View but not in browser. If you question is about doing business logic in View is then, read further.
MVC allows to plug any kind of view (mobile,desktop,web apps) to a controller. So view should not do any business logic else you will end up duplicating the business logic.
This LINK will help your understanding of MVC.
Data formatting in view not at all an issue but when you start implementing business logic in view that is the issue (I guess that's what you meant by use of linq in a View).
For instance inside a View, using linq on Model entities to loop through a collection and create a HTML table is perfectly all right, infact ViewModel should be tightly coupled to View.
[Trying hard not to be philosophical here but :)] In the end whatever architecture you use DO NOT limit yourself from thinking out of the box. Almost all projects use multiple patterns and most (good) developers solve business problems by unknowingly implementing a pattern. :)

Related

When should I query from a database in my view, ASP.NET MVC

Problem:
If I have a scenario where I don't want to change my model properties and need to get one more attribute from some table, is it fine if I write a query inside a view and show the result?
If the answer is no, I would like to know why it's not considered a good way.
In my opinion you should never do that. Just because you loose the entire paradigm of the tool you are using.
In a few years, this is confusing to you, or someone else maintaining the code. If you don't want to change it all, use dynamic properties, ViewBag or other options to keep your flexibility, test-ability, etc.
Yes.
View is not a mirror of your data structure. Actually, often it's an
aggregation and/or manipulation for user-friendly presentation of the data that stands behind.
In my opinion, you should never do queries in your Views. It's called MVC and the proper way of using it is to separate concepts.
You should have a Model, a Controller, a View and a Repository (as the simpliest approach). As the name suggests, View must be used only for displaying processed data.
More information about MVC best practices is here.
I remember when I started working with MVC. I didn't know about this and my teamleader told me it's never a good choice to do this.
Conclusion:
It's just a matter of design and perspective. If you're doing a project for yourself or for the university, organize your code as you wish. If you're working in a professional environment you should respect some working principles
Another important factor to think of, is this: if another person must refactor or modify your code he must know where to find methods, where to find models and so on.
First of all, the reason why it's called MVC is because of the separation of concerns. View's are only concerned of the User-Interface. Queries are done on the controller. Another is it would be too confusing if you would place everything in a single page which already defeats the purpose of having MVC.
Though there are cases when querying the database from a View may seem easier and appropriate, you should be ready for the consequences of breaking separation of concerns (SoC). When you spread your DAL across many layers it's going to be hard to re-factor the database in the future. Another question is security - if you decide to implement database security or controller-based security later, your view-based queries will be a security point.
However, if the project is small, I would trade SoC for performance.

CQS queries - Auto generate ADO Mapping to View models?

I am currently working on an MVC 4 application. I am planning to implement a command query seperation pattern to enhance performance and the structure of the application. I am happy with my commands - which map my view models to my entities use then use nhibernate to save my data.
The commands and queries will be running off the same database.
I am a bit unsure of the best approach to manage my queries. In my last project I used Stored procedures for all of my reads/queries, then used automapper to map my IDataReaders to my ViewModels. This worked ok but the main problem was the turn around time of writing the stored procedures and also when the domain model changed the stored procedures got out of sync.
Therefore, ideally I would like something that auto generated the views or sprocs from my view models. But realistically, I cannot see a way of doing this. As the Sprocs/Views need some knowledge of potentially more that one table. So simply reflecting on the View model properties would not be enough.
I could auto generate a table for each view model, read this during development, then once the domain was stable and before we went to test convert these to views/sprocs?
So I guess what I am asking is:
Has anyone managed to solve the sproc/view auto generation problem I described above? (this would be my favourite outcome!) Or even better has designed a much more graceful solution!
Or is it more sensible to only implement raw ADO reads where they are absolutely necessary - i.e searches, and there dispense with the need for lots of sprocs/views.
But then still separate out my queries into a separate channel (but inside some of them they use NHibernate, whilst others use my ADO reader).
(p.s I have looked at the other stackoverflow CQS related questions and I hope mine is different enough to warrant this question)
What do stored procedures solve for you? Why can't you use NHibernate for reads too? Are the queries NHibernate produces that bad?
If performance of reads is crucial for you, and the shape of your viewmodels is very different from how you store your model - making the denormalization process to a viewmodel too heavy to do on the fly, you might have to consider completely splitting reads and writes.
When you write something, you can raise an event - often done asynchronously - on which subscribers listening can store data on the readside in such a way that it's optimal for reads (close to the shape of your viewmodel). This would make querying really fast.
Since a picture says more than a thousand words..
You can read a good introduction to CQRS here.

Client based Table/Models

I'm new to MVC, I only done a basic tutorial with a standard application for editing an existing table, adding rows, view it, etc.
So there was a static view, static controller and a static model, which represented 1 table in the database.
Now I wonder how should that work, if I don't know yet, how the model is going to look like.
In my case, the client can first create a table, where he defines, which rows and what datatypes, etc. and then he can edit the table.
Is there a standard way for dynamic models, or is mvc the wrong way for this?
MVC works fine for this. With MVC, I just split each necessary bit of code up into the three categories. So try to think in an "MVC" Way.
The logic that is needed to connect to the database - Definitely a Model.
The displaying of the data in a structured table - Definitely a view.
The communication between the data gathered with the logic, and the displaying of that data - Definitely a controller
The idea of MVC is to separate the back end logic from the displaying of said logic. This helps to separate the two distinct parts of your project, and is generally considered good practice.
Hope this will help :)

Architecture of an ASP.NET MVC application

I'm in the process of doing the analysis of a potentially big web site, and I have a number of questions.
The web site is going to be written in ASP.NET MVC 3 with razor view engine. In most examples I find that controllers directly use the underlying database (using domain/repository pattern), so there's no WCF service in between. My first question is: is this architecture suitable for a big site with a lot of traffic? It's always possible to load balance the site, but is this a good approach? Or should I make the site use WCF services that interact with the data?
Question 2: I would like to adopt CQS principles, which means that I want to separate the querying from the commanding part. So this means that the querying part will have a different model (optimized for the views) than the commanding part (optimized to business intend and only containing properties that are needed for completing the command) - but both act on the same database. Do you think this is a good idea?
Thanks for the advice!
For scalability, it helps to separate back-end code from front-end code. So if you put UI code in the MVC project and as much processing code as possible in one or more separate WCF and business logic projects, not only will your code be clearer but you will also be able to scale the layers/tiers independently of each other.
CQRS is great for high-traffic websites. I think CQRS, properly combined with a good base library for DDD, is good even for low-traffic sites because it makes business logic easier to implement. The separation of data into a read-optimized model and a write-optimized model makes sense from an architectural point of view also because it makes changes easier to do (maybe some more work, but it's definitely easier to make changes without breaking something).
However, if both act on the same database, I would make sure that the read model consists entirely of Views so that you can modify entities as needed without breaking the Read code. This has the advantage that you'll need to write less code, but your write model will still consist of a full-fledged entity model rather than just an event store.
EDIT to answer your extra questions:
What I like to do is use a WCF Data Service for the Read model. This technology (specific to .NET 4.0) builds an OData (= REST + Atom with LINQ support) web service on top of a data model, such as an Entity Framework EDMX.
So, I build a Read model in SQL Server (Views), then build an Entity Framework model from that, then build a WCF Data Service on top of that, in read-only mode. That sounds a lot more complicated than it is, it only takes a few minutes. You don't need to create yet another model, just expose the EDMX as read-only. See also http://msdn.microsoft.com/en-us/library/cc668794.aspx.
The Command service is then just a one-way regular WCF service, the Read service is the WCF Data Service, and your MVC application consumes them both.

MVC way of handling data input

I have a data input module where I add the information of my product and its sub information like:
product basic info
product price info
product price details
price info and price details are related to product and are lists
In my web forms approach I would store my main product object on the view state and I would populate it's pricing info and details while doing ajax postbacks. This way I can create a compact module that is very user friendly in terms of defining a lot of data from one place without the need to enter these data from seperate modules. And when I am done I would do one product.save() and that would persist all the data to the respective tables on db.
Now I am building similar app on .net mvc framework and pondering on what would be the good way of handling this on mvc.
I don't resonate towards storing all this on client side till I click save. And saving to the db after each action makes me remember the days I was coding on asp.
Will appreciate your inputs on ways to approach this on mvc framework
I believe the best way of doing this is storing the data on the client side. It reduces unnecessary postbacks and improves responsiveness of your application. If you really want to store it on the server, you can use SessionState.
If you really want to store it in something like ViewState, you can go with a solution like this: ASP.NET MVC - Is there a way to simulate a ViewState?. However, I recommend against it as it will make things more complicated. Doing it client-side is probably the most elegant way and storing it in SessionState is the easiest.
Remember that you can always escape the MVC pattern and use a simple Web form for that specific page (which will give you ViewState where you need it): ASP.NET MVC controller actions design
store your Product list to the Model of the view and each time you change a value you can do a Ajax post to the controller and save the changes to the db, use partial views to display each item in your product list
you can try to integrate http://www.castleproject.org/ActiveRecord/ for easy saving and updating. That way you can just map your Model on your database using ORM(Object Relational Mapping). It takes a bit more work in the beginning but you will end up with simple commands like product.Update() and product.Create()

Categories

Resources