Good structure for ASP.NET MVC 4 / MVVM / Web API? [closed] - asp.net-mvc

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have a .NET MVC 4 project and just started Kendo UI MVVM framework. MVC uses ViewModels to send data from the controller to the view. I manage all my client side objects via the MVVM framework and use JSON to serialize them and send them back to my controller.
Currently I use the MVC ViewModel to return the data that will be static on my page and use jquery calls to fetch any dynamic data needed on my page. I find it confusing to have 2 methods to retrieve data. (And if I find it confusing, imagine the next developer that will have to work in my code)
I find it a bit useless to send the data to the View via ViewModels when I can easily have a structure where I query the controller (via Web API) on demand in my javascript code and save it into my MVVM view model directly.
I see a lot of advantages to using the MVVM framework in my UI, it makes control binding so much easier.
My question:
What is the best way to get the data from the controller to the MVVM ViewModel?
I feel that using the MVC ViewModel is duplicating work since I could query my Web API via ajax requests instead rather than translating my MVC ViewModel into my MVVM JS ViewModel.
Would it be a good approach to never return a MVC viewModel to my UI and always use client side Web API calls to retrieve all data?
Thanks,
Nicolas

Would it be a good approach to never return a MVC viewModel to my UI
and always use client side Web API calls to retrieve all data?
I would say it depends on your use case.
You could certainly return data that needs to be rendered the moment the page is displayed in the MVC Model. Remember that the MVC Model is rendered into the resulting HTML page on the server. This means that the values can be injected right into the HTML before it is returned to the client.
Also keep in mind that it could take overall longer to render your page completely if you have to hit the server multiple times; once to fetch the HTML then once for each Kendo widget to fetch data async.
That said, I usually end up doing what you said... Just render an MVC view with no Model, then have the Kendo UI widgets fetch their data after page load.
But really, it sort of depends on your data. If you have an MVC Model that contains:
public string Title { get; set; }
And in Razor you had:
<h1>#Title</h1>
Then that isn't really a case where I would want to re-fetch that data async. In those cases I usually do something sort of hacky, and put the value into the page:
<script type="text/javascript">
window.viewData = window.viewData || {};
window.viewData.Title = "#Title"
</script>
<h1 data-bind="text: Title"></h1>
<script src="viewmodel.js"></script>
Then in the viewmodel.js file (which I make a separate file from the returned HTML so that it can be cached by the browser)
(function (viewData) {
var viewModel = kendo.observable({
Title: viewData.Title
});
kendo.bind($("body"), viewModel);
})(window.viewData);
This is just my own approach though. It isn't necessarily the best for all situations. It all just depends what data you are pulling from where and how much.

From my understanding of the MVC architecture, View Model in MVVM and ViewModel in MVC are completely different from each other. What i can make out from your post is that you are using a framework with the help of which you are binding the data to the view. Can you elaborate on the framework or provide us with the code so that it can help others/me to get your question better.

Related

Knockout js over mvc [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have developed applications using .net MVC with razor view engine.
Recently I was going through knockoutjs being used for MVC applications.
From a 10000 feet bird's eye view , I see that both the approaches have the similar two way binding mechanism .
In the first approach razor syntax for binding the model and in the second we use the knockout data-bind attributes.
My understanding is , why is it that many people are nowadays preferring Knockout and all the buzz recently . Is there any major advantage of replacing razor syntax over knockout library?
They have nothing to do with each other.
ASP.NET MVC
As its name says, it uses MVC (model view controller) technology. That means that you have a model (all the business logic), that can be used to create view models to render the views (by using the razor template). The browser can post data to the controller, and the controller will usually answer by creating a new view model to render a new view, and send it as response to the browser.
So this technology basically uses the browser to send GET or POST requests to the server, and the server answers with rendered views. It can do it directly, or using AJAX. (ASP.NET MVC is much more versatile and can do much more than rendering views, but this is the basic idea).
So ASP.NET MVC involves the server in all operations: it must instance and use a controller, execute an action and send its result as response to the browser.
Knockout
This technology is completely different, in several regards:
it uses MVVM, which consist in a double-way binding between a view (HTML) and a model (JavaScript object). A change in any of the ends is applied automatically on the other end.
it happens on the client side, without using or depending on server resources (as far as it concerns Knockout)
it usually doesn't involve heavy business logic, but simple view models that can show and get data from the user.
This is all what Knockout can do for you. If you need to involve the server, and "heavy" business logic, you need to communicate with the server by sending and receiving objects, which you usually do in JSON format by exposing Web API services. (These services are usually implemented with ASP.NET Web API, but can also be implemented with ASP.NET MVC actions with JSON results, which it's a worse option).
Conclusions
So ASP.NET MVC involves the continuous use of controllers and communication between browser and server, while Knockout is a pure client side technology that doesn't need the server at all. Naturally, to make a Knockout application useful you usually communicate it with the server.
OTOH, Knockout allows to create a Single Page Application, which is a JavaScript application that can run by itself, without loading new full pages from the server, and which usually communicates with services, in the form of Web APIs. One advantage of this is that the application can work even without a server on the other side, and is much more responsive, because it doesn't depend on comminucating with a server to refresh the view.

Server Side and Client Side MVC [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have started learning ASP.Net MVC, I have few questions with regards to MVC framework [Client Side or Server Side]. You might find these questions stupid but I am really confused and would like to clear my doubts.
Here it is....
ASP.Net MVC, is it server side or client side framework?
Let's say my controller methods getting data from the SQL Server, I convert it into JSON and updating the MVC view, in this case
A. Is it called as Client side data binding or Server side binding?
B. While retrieving the data from database using controller method, do i get entire HTML along with data in the response or just the data that I have requested for?
In ASP.Net, lets say I am inserting data in database on button click event and If I am not wrong, in this case it will submit the entire page to the server, how button click event works in ASP.Net MVC?
I have also read that we can use Angular.JS or knockout.JS with ASP.Net MVC, what purpose Angular.JS or knockout.JS would solve if we use it with ASP.Net MVC?
Regards
ASP.Net MVC, is it server side or client side framework?
> MVC - is Model View Controller - its All-in-One
Let's say my controller methods getting data from the SQL Server, I
convert it into JSON and updating the MVC view, in this case
Is it called as Client side data binding or Server side binding?
> Server side is ALL what you do with C# (In class library/controllers etc)
While retrieving the data from database using controller method, do i
get entire HTML along with data in the response or just the data that
I have requested for?
>If you will use knockout / angular - then you need just get data from server, and data-bind will happen automatically
In ASP.Net, lets say I am inserting data in database on button click
event and If I am not wrong, in this case it will submit the entire
page to the server, how button click event works in ASP.Net MVC?
>Or with submit form (to action url) - or with client framework (knockout/angular) - you just send json
I have also read that we can use Angular.JS or knockout.JS with
ASP.Net MVC, what purpose Angular.JS or knockout.JS would solve if we
use it with ASP.Net MVC?
>Angular more rich framework. In knockout we have only data-bind with html. It depends on what you need for your project.
ASP.Net MVC is a server side framework. (An alternative is ASP.Net WebForms: your events are posts to the same page, abstracted to seem like desktop application events.)
If you want, you can output data as JSON or XML and use this with a client side JavaScript framework to update your views.
You will not have button clicks in ASP.Net MVC. All data is sent to the server as parameters in the URL, GET or POST variables (in truth, WebForms also does this). You can grab the values directly from the Request or use the bindings from MVC to get the values as action parameters.
These frameworks are used to build the views in the client side. To use them, you will have to, mostly, output JSON from your controllers.
MVC is a design pattern that you can apply "anywhere" - e.g. server or client side. In ASP.NET MVC, the MVC pattern (model, view, controller) is first and foremost applied server-side, e.g. the code you write executes on the server. (In your view, you can if you like also utilize some MV* pattern, using your own code or a library like Knockout or Angular. This (JavaScript) is then executed on the client, hence client-side.)
Sometimes a piece of code or software that communicates with some other service or similar is labeled a "client", but that is a different context.
Your binding example would execute on the server, if we're talking about ASP.NET MVC Controller code. (In general, there is no need from the framework point-of-view to do any explicit JSON conversion, but that's a different question.)
ASP.NET MVC features something called "model binding" (google it). It's there out-of-the-box, but you can control it with your own implementations as well. Thanks to this feature, you normally deal with strongly typed data inside your Controller.
ASP.NET MVC and Web Forms are fundamentally different. Explaining exactly how, and how to make buttons in ASP.NET MVC that send data is out of scope, but generally we're talking simple POSTed data, e.g. from an HTML form or whatever.

Asp.net mvc web application with asp.net web apis

I am new to the Asp.Net MVC. I am doing asp.net web application. I have data layer which I want to be exposed from the MVC Web api only. For web api project i used entity framework as a model and for mvc application i am using entity classes. I am calling the web api from the view with jquery and perform all the operations.
Is that right approach or need to use some jquery framework. Or is there any projects available which uses asp.net web api's only. I warm up google for so many times but didn't find essential. Please assist me here.
You can use jQuery or any javascript framework you please to retrieve data from your API. You could even use raw javascript if you really wanted to. However, if most of your logic is going to live on the client, you'll probably want to look into some MVC/MVVM/MVP javascript library/framework to keep things organized.
A good place to start is the Single Page Application template that is built into Visual Studio 2013 and available for 2012. It uses .NET MVC to load up the HTML markup, styles, and scripts, and then uses Knockout.js to structure the application and send & retrieve data from a Web API controller located in the same app. It's also worth noting that you can grab templates that use other popular javascript frameworks like Ember, Angular, Backbone, Durandal, and more. If you'd prefer one of those frameworks over Knockout then download one of those templates and look through the code.
Without seeing any code, it sounds like you have the right idea. You can use any client side framework of your choice to interact with your Api Controllers (Knockout, Angular, Ember, Backbone) or you can use straight up jQuery.
Since you are new to ASP.NET Mvc, a little clarification on the differences between the traditional Mvc Controller and the new Api Controller seems in order. In traditional MVC the controllers works to select which view (UI) to display married to data (the model):
public ActionResult Index()
{
var theData = serviceLayer.GetData();
return View("Index", theData);
}
You can also return pure JSON data from a controller:
public JsonResult GetMyData()
{
var theData = serviceLayer.GetData();
return new JsonResult()
{
Data = theData
};
}
This had the problem of making it difficult to determine the names of the endpoints that retrieve UI vs the endpoints that retrieve data. The Web Api is Microsoft's implementation of a RESTful framework. Instead of a controller with many different methods (Index(), GetSingle(), GetMany(), List(), DoSomethingElse(), DoAnotherThing(), etc.), the Api controllers usually contain only methods that correspond to the HTTP Verbs: GET, POST, PUT, and DELETE. The same endpoint can then be called differing only by the verb you are using. Take the following endpoint for example:
http://mydomain.com/api/customer/1234
Calling this endpoint will do the following for Customer with id=1234:
GET will return the data
PUT will update the data
DELETE will delete the data
In addition to making it clearer for your own development team, the Api also makes it easier for you to expose your data to third parties. You would need to provide a root URL and a list of your objects and any developer would be able to use it. There are other things you would need to do such as implementing security tokens but I wanted to demonstrate the benefits of using an easily understood framework.

Razor templates, views and angular.js

TL;DR
What are the best practices when using .NET Razor views and AngularJS?
Context
We are developing a public website (not an intranet application) using mvc4 with razor, and we weren't very familiar with client script, so we started with what we knew: jQuery.
But now things are getting more complicated and we'd like to switch to AngularJS.
On the .NET part, we use Razor templates and UIHintAttribute (plus some custom ones) to render the right html "control". We also add custom html attributes to give extra information to the jQuery part (like title for a tooltip....)
So we already use a declarative way of setting the user interface behavior, that's why AngularJS seems a good option.
Questions
Since we already have models defined server side, and since AngularJS also uses models, wouldn't it force us to duplicate code?
How do we deal with data binding feature, since we already do some binding server side (in the views). Should we make a completely asynchronous application, making AJAX calls from AngularJS to load data, or can we mix both?
Anything else we should be aware of when trying to use both of these technologies?
I did some research on Google, but I can't find detailed ways of mixing Razor views and templates with AngularJS... Perhaps that's just not a good thing to do?
We dealt with this issue for months when working with MVC plus another JavaScript framework (Knockout). Ultimately, if you're going to be using a client-side MV* framework for rendering your user interface, you will find that mostly ditching Razor is going to be your best bet.
Most of the major MV* JavaScript frameworks, including AngularJS, assume you will be maintaining UI state and rendering your user interface based on JavaScript models or view models. Trying to mix in server-side rendering is just not going to work very well.
That's not to say there is no use for MVC when it comes to developing an Angular application. You can still take advantage of some great features like ASP.NET Bundling and Minification. And sometimes it works really well to embed JSON directly into the page using a Razor view or partial as opposed to making an additional AJAX call.
As for models, you may want to take a look at Breeze.js. It's a JavaScript library for data access that goes great with ASP.NET on the server side to share model metadata.
We wrote our own data binding mechanism that synchronizes the angular.js model with a view model on the server side. The javascript model is generated from a JSON serialization of the server-side view model to avoid the duplicate code that you were talking about.
We are using SignalR to update the client's view model from the server.
Server-side changes of the C# view model properties are sent to the client as a packet containing the path to the property, e.g. Persons[42].Address.City, and the value itself, e.g. New York. The view model inherits a base class that takes care of generating the property path, so the actual view model looks quite clean and we can concentrate on business logic.
Client-side changes of the javascript view model properties are sent to the server in the same way. To catch the change events, we encapsulate all fields of the original javascript model in get/set properties where the setter sends the update packet to the server.
Server-side methods of the view model can be invoked in a similar way. All objects in the view model have an invokeMethod function that can be used like this: Products[42].Manufacturer.invokeMethod('SendEmail', 'mailsubject', 'mailbody'). This will send a packet to the server containing the method path Products[42].Manufacturer.SendEmail and the arguments as an array of ['mailsubject','mailbody'].
In conclusion, the html view (kind of) binds to the view model on the server side where other systems, such as regular Razor views can work on the same objects.
The source code can be found here: SharpAngie.

Way to keep state in MVC2 without Session or Query string?

Is there a way to keep information between post backs in MVC2 without utilizing Session variables or the query string?
You mean like the view state from .NET Web Forms? Technically there is, although it isn't recommended - you're much better off utilizing models and posting the model data to the server and pushing the model back into the view.
This will work well but if you're needing something as stateful as the WebForms ViewState, I would recommend doing your project in WebForms or use the session to save your models.
Edit: Build your form that posts (or gets) data back to the same page. Then in your controller, have a method like this.
[HttpPost]
public ActionResult LoginUser(LoginViewModel model)
{
//work on the model here
return View(model);
}
This will push the form data that the user just submitted back into your view. Then have an Html helper like this in your view.
<%: Html.TextboxFor(m => Model.Username) %>
There are a slew of excellent resources on the web about using html helpers with models. Google around and you'll come across them.
You could use Hidden Form fields to POST the values back to the server with each form submission.
Other alternatives include a cookie or Http Cache - what is stopping you using session?
As a high level concept, you should rely as little as possible not only on Session to store your state, but on statefulness in general in a web application. The idea is that the web itself is stateless by design, and when designing software on that paradigm the software should be designed to embrace a stateless nature.
More specifically, using a ViewModel gives you a strongly typed representation of the data needed for your view to pass down to the client. Pieces of that data which hold information about the state of a given request which can be made from that view can be added to the view in probably a number of ways, but the two most immediate ones are:
As hidden form field elements
As parts of URLs for requests
Check out the NerdDinner tutorial for a standard approach to using either ViewData or a strongly-typed ViewModel. Some Google searches will, as always, yield more information and tutorials. But note specifically where the tutorial uses the ViewModel properties in the view. These can be used anywhere in the rendering of the HTML, either in the HTML helpers or in manually constructing the tags.
Additional interesting reading regarding the statelessness of the web (and this whole not-as-new-as-many-people-seem-to-think REST thing) is the article: How I Explained REST to My Wife.
If your main issue with the Session variables is of a practical nature (want something that works for a single request, not needing to worry about cleaning it up etc) rather than a requirement to not use Session then use the TempData dictionary. It deals with putting information in the Session for a single request only and the framework will automatically remove it for you afterwards.

Resources