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

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.

Related

Pass javascript parameter to partial view in asp.net mvc

lets say I want to a partial view like the following sample
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
in the jsparameter I want to pass as a parameter that is the result of a javascript function. Maybe this is not logical because javascript runs on the client, but how can I achieve a similar functionality ? thank you in advance
If you need to call a part of a page based on some actions or values determined by actions on the client side, then you should think to use JavaScript (preferably jQuery) and Ajax.
Through jQuery-Ajax, you could easily call a Partial view through the Contoler and since it's a regular HTTP request, you would be able to pass all the parameters you need.
Using code as :
#Html.RenderAction("ListDocuments", "MultiFileAttachments", new { id = jsparameter });
is not possible since it is rendered by the server before it's sent to the client browser.

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?

Can i pass JSON instead of Model from my controller to my Razor view

I have a view that inherit the following:-
#model MvcApplication.Models.Application
But i need to know if it is possible to pass JSON objects to my view in the same way i am passing the model objects?
Since i have the following Controller:-
public ActionResult ListPackages()
{
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
//code goes here ....
return Content(json, "application/json");
}
}
which returns JSON using a API call, and then i am displaying the JSON on the view using JavaScript as follow:
$.ajax({
url: $('#geturl').data('url'),
type: 'GET',
cache: false,
success: function (result) {
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
}
The problem with displaying the JSON using JavaScript is that it will make too difficult for me to work easily with the JSON objects, such as creating links based on the returned JSON or creating table that contain the JSON. So my question is: Is it possible to pass a JSON object instead of a Model object from my controller to my view?
Server- vs client-side confusion
You're talking two things here:
Creating a view: controller passes model to the view on the server side and it doesn't make much sense to do so using JSON, because an in-memory object is being passed to view engine.
Consuming JSON data on the client: what you're talking about here is client-server Ajax communication where you request data from the client and get JSON returned from the server. This has arguably nothing to do with model data being passed to the view
Best solution using JSON
In order to easily consume JSON data (in your case it's an array of packages) on the client to generate resulting populated HTML is to use some sort of templating on the client side. jQuery used to have non-final templating plugin which is now a separate project. I've had great experience with it but there are other plugins as well. Use the one that you feel most comfortable with its syntax.
Where to put those templates?
If you know the structure of your JSON objects passed from the server at the point of creating your view, you can put templates in the view itself and they'll just wait untill being used on the client.
If you don't know the structure of your JSON objects then you'll have to pass templates either along JSON object or as a separate request.
The first approach is the usual one, the second one is rarely used and is much more dynamic.
Best solution not using JSON
If you don't like parsing JSON to HTML results (either manually or using templates), you can always make Ajax requests to your controller action, which would return a prepared HTML as a partial view instead of JSON result. This way, you could easily just put that HTML onto your page without any JSON data manipulation.
What do you gain here? Well suppose you have this functionality in your app:
You have a view that displays a paged list of packages.
When user first accesses the page first page of packages are being returned
Paging to next page is done via Ajax and the list is being replaced by returned data
If you'd create a partial view for your subsequent Ajax request, you can use the same partial view in your main view to display the first page of packages. This will ensure that you only have to change one partial view and display would change on inital page load as well as subsequent package paging.
If you used view + JSON + templating that means that you have to maintain two presentations of package list: the one being used in the view for the first page and the template that displays subsequent paging.
Which one then?
All things being equal it makes the second solution better. But the choice of course depends on your case (of things not being equal) and you should be able to determine which one is best in your scenario.
No, you can't. A view must be strongly typed to a model. So one solution would be to deserialize this JSON into a model object before passing it to the view:
public ActionResult ListPackages()
{
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
//code goes here ....
var model = new JavaScriptSerializer().Deserialize<MyViewModel>(json);
return View(model);
}
}
where MyViewModel would of course reflect the JSON structure that you are working with.

Controls without views for globals functions in asp.net MVC (with razor)

The well described model of View/Controller/Model is quite clear when it comes to object (say a book) update/delete/save etc...but how do you guys organize the common code such as populating drop down lists (from db)?
I use Jquery ajax to call control's action, but in cases such as getting the arrays for drop down lists, I feel like these should not reside in the same BookController .
Can I have a Controller without the matching view for these purposes only?
Thank you
Each ViewModel is data for a View to render. It sounds like you understand that. When Ajax calls for Data, I think it makes more sense for the controller for the view be responsible for creating another ViewModel and returning it as Json for the rendered view. If mutliple views need to retrieve a list of Books, should call /Books/AjaxList (bad method name example), just like any view under /Books. Seperating the responsibility of creating a ViewModel based on Ajax or not Ajax doesn't make sense to me.

ASP.NET MVC 2 AJAX dilemma: Lose Models concept or create unmanageable JavaScript

Ok, let's assume we are working with ASP.NET MVC 2 (latest and greatest preview) and we want to create AJAX user interface with jQuery. So what are our real options here?
Option 1 - Pass Json from the Controller to the view, and then the view submits Json back to the controller. This means (in the order given):
User opens some View (let's say - /Invoices/January) which has to visualize a list of data (e.g. <IEnumerable<X.Y.Z.Models.Invoice>>)
Controller retrieves the Model from the repository (assuming we are using repository pattern).
Controller creates a new instance of a class which we will serialize to Json. The reasaon we do this, is because the model may not be serializable (circular reference ftl)
Controller populates the soon-to-be-serialized class with data
Controller serializes the class to Json and passes it the view.
User does some change and submits the 'form'
The View submits back Json to the controller
The Controller now must 'manually' validate the input, because the Json passed does not bind to a Model
See, if our View is communicating to the controller via Json, we lose the Model validation, which IMHO is incredible disadvantage. In this case, forget about data annotations and stuff.
Option 2 - Ok, the alternative of the first approach is to pass the Models to the Views, which is the default behavior in the template when you start a new project.
We pass a strong typed model to the view
The view renders the appropriate html and javascript, sticking to the model property names. This is important!
The user submits the form. If we stick to the model names, when we .serialize() the form and submit it to the controller it will map to a model.
There is no Json mapping. The submitted form directly binds to a strongly typed model, hence, we can use the model validation. E.g. we keep the business logic where it should be.
Problem with this approach is, if we refactor some of the Models (change property names, types, etc), the javascript we wrote would become invalid. We will have to manually refactor the scripting and hope we don't miss something. There is no way you can test it either.
Ok, the question is - how to write an AJAX front end, which keeps the business logic validation in the model (e.g. controller passes and receives a Model type), but in the same time doesn't screw up the javascript and html when we refactor the model?
Stick with Option 2, but there are ways to test the code. You can use a web application testing tool like WatiN or Selenium to perform integration tests on your HTML pages. Also, FireUnit gives you the ability to unit test your JavaScript code (you'll need Firefox and Firebug in order to use it).
In the spirit of full disclosure, I haven't tried out MVC 2 yet. However, I've been using MVC 1 for some time now and have used these tools with some pretty good results.
Problem with this approach is, if we
refactor some of the Models (change
property names, types, etc), the
javascript we wrote would become
invalid.
I dont see how changing a property of the model changes javascript-code. Usually you hijack the submit event of a form and submit it via ajax. No properies envolved, a long as you take option 2.
Changing properties might break your MVC - application, but thats not specific to ajax.

Resources