ASP.NET MVC, Knockout, Web API - Formatting Concerns - asp.net-mvc

I am using ASP.NET MVC / WebAPI and Knockout to generate my views. I am trying to figure out where I should handle formatting, url generation, etc (I would normally do in my controller and return a view model).
Is is an ok practice to have my WebAPI return view models with preformatted data or should I leave that to the caller?
Please note the API is only used by my application

What I'd suggest is the following:
WebApi controller actions provide / consume data (json data) - Http verb actions
On your knockout viewmodel it contains methods to get / save etc the json data which is called on document ready to populate the data
The default mark-up is created by your MVC view returned from the controller on initial load and then any further can be done dynamically (either inline or templates; native or knockout)
In my opinion the WebApi should not return the full view model. It should only return the data consumed by your view model. The api points should not be implementation specific and allow for knockout consumption as well any other client.
HTH

Related

ASP.NET MVC 4 Web API & Knockout.js

I´m starting a Proof-of-concept SPA using the new Web API and Knockout, so far I´ve managed to create the API controller, consume it with Knockout and map entities and arrays using Knockout mapping.
I´m now trying to create a simple CRUD, but I can´t get my head around as to how to implement the ViewModels.
So far I´ve come up with 2 options, listed below:
I can define a ViewModel on the server, that contains the entity´s attributes, plus an array of the same entity. When I enter the CRUD functionality, I call the server and retrieve that ViewModel, with the entity list and the attributes for creating a new entry.
I can define 2 ViewModels, one with the grid data, and another with the entity´s attributes. When I call the CRUD functionality, I get the grid data, and when I want to edit/create a new entry, I call the server and retrieve the ViewModel for that.
On both options I use one single view, which contains the grid definition, and the edit/create form format, which I display on a JQuery pop-up.
I can´t figure out which would be the best option, I´m starting to lean towards the 2nd one, but some guidance would be appreciated.
Thanks in advance!
Do you really need to call the server at the point that you launch the Create / Edit dialog? Could you not have, say, an ObservableArray of EntityVM (a Knockout view model) as the binding source of your grid, and when you either click Add New or click an existing item, the Create / Edit dialog is made visible (that could be done with binding too) with either an empty EntityVM as its data source or a populated EntityVM copied from the grid source's item? Then when you click Save, Ajax the entity as JSON to the server and return a JSON response representing the updated grid data? Or is that not the right understanding of your context?

ASP.Net Web Api + KnockoutJs + MVC4 - Tying it together

I am starting a new project, and keen to make use of the KnockoutJS + Web Api which are new to me, I have a good understanding of the Web Api, but Knockout is tough to get my head around at the moment.
This is my initial thoughts of how I want my app to work:
I have a standard MVC controller such as LeadsController
LeadsController has an Action called ListLeads, this doesn't actually return any data though, but just returns a view with a template to display data from Knockout.
The ListLeads view calls my api controller LeadsApiController via ajax to get a list of leads to display
The leads data is then mapped to a KnockoutJs ViewModel (I don't want to replicate my view models from server side into JavaScript view models)
I want to use external JavaScript files as much as possible rather than bloating my HTML page full of JavaScript.
I have seen lots of examples but most of them return some initial data on the first page load, rather than via an ajax call.
So my question is, how would create my JavaScript viewModel for Knockout when retrieved from ajax, where the ajax url is created using Url.Content().
Also, what if I need additional computed values on this ViewModel, how would I extend the mapped view model from server side.
If I haven't explained myself well, please let me know what your not sure of and I'll try and update my question to be more explicit.
I think your design is a good idea. In fact, I am developing an application using exactly this design right now!
You don't have to embed the initial data in your page. Instead, when your page loads, create an empty view model, call ko.applyBindings, then start an AJAX call which will populate the view model when it completes:
$(function () {
var viewModel = {
leads: ko.observableArray([]) // empty array for now
};
ko.applyBindings(viewModel);
$.getJSON("/api/Leads", function (data) {
var newLeads = ko.mapping.fromJS(data)(); // convert to view model objects
viewModel.leads(newLeads); // replace the empty array with a populated one
});
});
You'll want to put a "Loading" message somewhere on your page until the AJAX call completes.
To generate the "/api/Leads" URL, use Url.RouteUrl:
<script>
var apiUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "Leads" })';
</script>
(That's assuming your API route configured in Global.asax or App_Start\RouteConfig.cs is named "DefaultApi".)
The knockout mapping plugin is used above to convert the AJAX JSON result into a knockout view model. By default, the generated view model will have one observable property for each property in the JSON. To customise this, such as to add additional computed properties, use the knockout mapping plugin's "create" callback.
After getting this far in my application, I found I wanted more meta-data from the server-side view models available to the client-side code, such as which properties are required, and what validations are on each property. In the knockout mapping "create" callbacks, I wanted this information in order to automatically generate additional properties and computed observables in the view models. So, on the server side, I used some MVC framework classes and reflection to inspect the view models and generate some meta-data as JavaScript which gets embeded into the relevant views. On the client side, I have external JavaScript files which hook up the knockout mapping callbacks and generate view models according the meta-data provided in the page. My advice is to start out by writing the knockout view model customisations and other JavaScript by hand in each view, then as you refactor, move generic JavaScript functions out into external files. Each view should end up with only the minimal JavaScript that is specific to that view, at which point you can consider writing some C# to generate that JavaScript from your server-side view model annotations.
For the url issue add this in your _Layout.cshtml in a place where it is before the files that will use it:
<script>
window._appRootUrl = '#Url.Content("~/")';
</script>
Then you can use the window._appRootUrl to compose urls with string concatenation or with the help of a javascript library like URI.js.
As for the additional computed values, you may want to use a knockout computed observable. If that is not possible or you prefer to do it in .Net you should be able to create a property with a getter only, but this won't update when you update other properties on the client if it depends on them.

ASP.NET MVC 2 ExtJs and Ajax post array of objects to controller?

I'm developing an ASP.NET MVC2 web application.
I want to send an array of JSON objects from my view code using AJAX to the controller.
I have seen many examples of hot to do this using jquery.
However I would like to know how to do this using an Ajax request without using jquery?
I have read that updating to MVC3 may help, if this is the best solution can you point me in the right direction on how to update from MVC2 to MVC3?
Below is some sample code:
VIEW
var modRecords = store.getModifiedRecords();
Ext.Ajax.request({
url: AppRootPath +'EmployeeDetails/SetSAASUser',
params: {
users: modRecords
}
});
CONTROLLER
public JsonResult SetUser(IEnumerable<User> users)
{
GetData data = delegate
{
return Repo.SetUser(users);
};
JsonResultBase jsonResult = GetJsonResult(data);
JsonResult json = PortalJsonResult(jsonResult, JsonRequestBehavior.AllowGet);
return json;
}
To MVC3 or not to MVC3
No particular need to convert to MVC3 though because you can consume JSON in MVC2 as well. There are two actually many ways of doing it:
using JsonValueProviderFactory which Phil Haack described in his blog post that would give you exactly equivalent functionality as if you've used MVC3.
Pre-convert your client data so ExtJS will correctly send it to the server. This is somehow similar to what I've done with a jQuery plugin. A very similar thing could be done with ExtJS as well. These two steps are necessary to accomplish it:
First you'd need to analyse how your JSON object is converted on the wire (use Fiddler)
Write code that transforms your JSON into a form that will be correctly sent to the server. What form would that be? You can read about that in my previously mentioned blog post.
I don't know if you're aware of this but there's also something called Ext.Direct for ASP.NET MVC that may help you in this scenario. As it says it support simple, complex and array parameters which covers it actually.
The only advantage of using MVC3 is that JsonValueProviderFactory is enabled for you by default without any additional code.
I've used ExtJS few years ago when it was in version 2. No Ext.Direct and MVC back then yet. But we were very successful in pairing it to an Asp.net WebForms application with async calls to WCF using the same business+data layers as Asp.net WebForms application used.

ViewState vs ViewData in mvc?

What is the difference between viewstate and viewdata in mvc?
I was just going through the MVC framework & the exact question popped up in my head.. I understand the difference as below.
ASP.Net & MVC are two different worlds. But looking closely they are not. The concepts of web remains the same and it just the way to write the code. Ok letz compare them
ASP.Net
.aspx -- So this is the view which contains the html to be rendered in the browser
.aspx.cs -- as we know this is the code behind for doing all the manipulation of the html
So on top of that we have the BO with our properties and which is bound to the controls using databind.
So here comes the ViewState which remembers the data bound to the controls back and forth between the postback.
MVC
View - this holds all the HTML code which in turn is still a .aspx or ascx file
Controller - has the logic behind the HTML. Inside that you have the action methods for performing the specific actions.
So here instead of BO, you have the Models with the same properties which is given to the View to render itself in a different syntax instead of a databind.
Now ViewData is used to bind the anonymous data between the controller and the view.
Comparatively ViewData is more organized and easy to use but apart from that they serve a similar purpose but different in few ways. Like Viewstate is persistent between postbacks and ViewData is not as MVC is stateless.
Hope this explains to an extent
ViewState and ViewData can handle some complex objects.
ViewState is within page lifecycle while ViewData works in very different way. ViewData can be passed to the target view.
Please refer here for understanding of viewState:
http://msdn.microsoft.com/en-us/library/ms972976.aspx
for viewData:
http://www.asp.net/mvc/tutorials/asp-net-mvc-views-overview-cs
hope that helps
View state is used only in ASP.net forms,controls and Page life cycle. View state is used by ASP.net framework to manage control states.
View Data is a dataset or Data which is passed to your View - to dipslay HTML data in MVC,
Viewstate is not used in MVC. Please refer above mentioned links for more details.

How to update Model in MVC

I'm wondering how you keep a constant value of the Model in an ASP.NET MVC framework. Like when adding something to the Model through the view. You go back to an action in the controller but where do you keep the Model? Is it a private in the controller? or is it passed back and forth from the view to the controller because if it gets big then you are passing alot of data back and forth to add/delete a single item from the Model.
Also any small examples to show this?
Thanks
What are you referring to? Are you meaning a database table loaded up into an object such as Ruby on Rails's ORM -- typically the 'Model' is a series of interfaces or domain objects that load data into objects from the database .. or more simply just the database period.
Please be more specific. There are many MVC frameworks and many different kinds of 'Models'
I think you should check out a ASP.NET MVC tuturial like NerdDinner (from "Professional ASP.NET MVC 1.0"). Scott Guthrie has posted a html version of the tutorial on his site. It's a fairly simple site that they build in the tutorial, and is a great intro to ASP.NET MVC (in my opinion).
There are also some good tutorials on the ASP.NET site.
Hope these help you with .NET MVC, it's a great framework to use!
You can pass the model to the page and you can then use UpdateModel(model name) within your controller.
Each member in the model must be a property with a getter and a setter.
On the page you can hold the data in say a hidden field if you need to maintain the value outside of state.
If you have problems using UpdateModel then you can use the following in your controller;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(int? id, FormCollection collection)
{
string commentText = collection["myFieldName"];
}
This will normally get your values from the model.
Hope this is what you were asking.
Think of the model as a data transfer object. In a list, display only or edit page, you pull it out of a data layer as a single object or a list of objects. The controller passes it along to the view and it gets displayed.
In the case of an insert, a new data transfer object is instantiated upon post back and is updated with the posted values. Then sent back to the the data layer for persistence.
In the case of an edit, it comes from the data layer on the HTTP GET request and is used to pre-populate the HTML form. Then on post back, the data transfer object gets updated with the posted values and sent back to the the data layer for persistence.
Definitely checkout NerdDinner or Stephen Walther's samples.

Resources