How to get view model directly in layout? - asp.net-mvc-3

I'm working on a practice where I minify most of my javascript in static files, and then each view has something like this:
#section Script
{
#Html.Action("MinifyJavaScript", "Resource", new { viewPath = "~/Views/User/Register.Js.cshtml", model = Model })
}
Which in turn renders the tiny, non-static, pieces of javascript code, like the one below:
#model UserRegisterModel
<script>
(function ($, b) {
$(function () {
b.views.user.register('#Url.Action("ValidateInput", "User")');
});
})(jQuery, bruttijjimo);
</script>
This allows me to cache javascript in views more heavily, since only the parts that vary with the model can change (and are generally treated as partial views)
Now I'd like to further upgrade this practice by removing the need of a layout section, and by convention, render the javascript partial view (which is passed the same model as the view) right after the view. I already created the method to compress the javascript in the view. And there's also the convention that javascript for a view must be in a .js.cshtml file, and share the model with the view.
What I'd need is to grab the model for the view from the layout, and the name of the view, too, and render it there.
This would only work or be needed for the actual view, since partials use a script manager if they need to emit javascript.
So: how can I grab the model for the view from the layout? The rest I can figure out, but this one is eluding me..

So: how can I grab the model for the view from the layout?
#Model should give you what you are looking for.
This being said I didn't quite understand what you are doing but the fact that you have javascript inside your view instead of having it in a separate javascript file and leaving the caching stuff to the browser and reinventing some wheels kind of feels wrong.

Related

How to make a laravel 5 view composer

I'm still learning Laravel and I'm working on a small project to help me understand better. In the project, I am in need of a global array, so that I may display it or its attributes on every view rendered. sort of on a notification bar, so that each page the user visits, he/she can see the number of notifications (which have been fetched in the background and are stored in the array).
I have done some research, and realized that I have to fetch and compile the array in a view composer I think. But everywhere I go, I cant seem to understand how to make a view composer.
I need to fetch the relevant rows from the database table, and make the resulting array available to each view rendered (I'm thinking attaching it somehow to my layouts/default.blade.php file.). Please help, any and all advice is greatly appreciated:)
You can now inject services on your view
More info here: https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/2
You have to use Sub-Views of laravel blade. I guess your functionality is like a sidebar or like a top bar which will be rendered at every page.
//Your Controller pass data
class YOUR_CONTROLLER extends Controller {
public function index()
{
$data = YOUR_DATA;
return view('YOUR_VIEW_FILE', get_defined_vars());
}
}
//In Your View File
#extends('LAYOUTS_FILE')
#section('YOUR_SECTION')
#include('YOUR_SUB_VIEW_FOR_NOTIFICATION')//You need not pass any data passed all data will be available to this sub view.
#endsection
In your sub view
//Do what ever you want looping logic rendering HTML etc.
//In your layout file just yield or render the section that's it
#yield('YOUR_SECTION')
More explanation can be found Including Sub-Views

How do I rebind the knockout viewmodel when the page is loaded in as a partial via ajax?

The page that I'm working with has a couple tabs and the content of each tab is loaded in via ajax by requesting a partial view from the controller. The problem is that the partial view uses knockoutjs, so it is bound to a view model. In this particular scenario, the page is loaded up in its entirety first time through, so all of the bindings work fine. When you switch tabs, it requests a partial view and replaces the tab content area with the new page. When you switch back to the first tab, it'll successfully loads the partial, except it would appear that all of the knockout bindings have been lost so there is a lot of missing data.
I can't place the viewmodel declaration and model bind in the partial because jquery hasn't been loaded by that point. Or so it would seem ($ is not defined).
The view model is declared and bound on the main page that calls the partial view(s), not the partial view itself, so I thought the model would still be available and bind successfully, but it does not. I know I'm doing this wrong, and partial view are super wonky when it comes to javscript so I'm hoping to steal a bit of insight from you guys.
Here's the basic setup:
If you are able to bind to specific non-overlapping areas of the page, then you could choose to call ko.applyBindings(someViewModel, someDomElement) like in this answer: Can you call ko.applyBindings to bind a partial view?
However, if you have an overall view model bound to the page and then "islands" of content that are loaded via a partial that you want to bind later, then one option would be to go for something like this: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html. So, you would set up a binding on the container of where your partial goes that tells Knockout to keep its hands off of that area. Then when you load the partial, you can safely call ko.applyBindings(someViewModel, innerContainer).
The binding might look like:
ko.bindingHandlers.stopBinding = {
init: function() {
return { controlsDescendantBindings: true };
}
};
and you would use it like:
<div id="outerContainer" data-bind="stopBinding: true">
<div id="innerContainer">
...load your partial here
</div>
</div>
Then, ko.applyBindings(someViewModel, document.getElementById("innerContainer"));

Ember.js and Isotope.js - Executing Javascript after all childviews became rendered

I use Ember.js (1.0. RC) and would like to apply Isotope.js's functionality to some of my views located in a "container".
So my route basically loads the models containing the needed data from a server, sets up the controller's content and binds it to the model's data, which works fine.
Next I declared a template for my IndexRoute which iterates over all the loaded items like this:
{{each item in this itemViewClass="App.ItemView"}}
The items are the images that should be filtered with isotope.js. ItemView only refers to a simple template for the time being.
The execution chain is the following: Route -> Fetching model data -> Set up controllers -> Create IndexView -> Pile up all the ItemViews in a DIV-container.
Now I need to check whether all the ItemViews are loaded and the rendering is finally finished to apply isotope.js's filtering functionality but I can't figure out how to do that.
The didInsertElement of the IndexView event fires as soon as it's been rendered and before the ItemViews were added to the DOM.
I already tried to set up a ContainerView which would work in conjunction with Ember.run.scheduleOnce("afterRender"...) if I didn't fetch the data through the models but hardcoded it to the content variable.
The CollectionView also did me no favor with this exercise.
Any ideas how to solve that misery? I'd really appreciate it. Thanks.
I am not sure how exactly isotope.js works..considering its just a jquery plugin, you can call isotope like this even if it is a ContainerView or CollectionView.
didInsertElement: function() {
Ember.run.next(this, function(){
this.$().isotope({}) // or watever code u want to write
});
}
This makes sure that the code inside ember.run runs once rendering is done completely..

Knockout JS, MVC 3 and View Model Server Side Data as JSON

So I have a problem...I am separating concerns in my web app: HTML in razor pages and JS in js files. My problem lies in the fact that I want to use data from my controller passed down in the view model from the server as the options of a select list. The problem lies in the fact that I have separated my js from my HTML and I can't access Razor inside the js files.
I have a list of items coming down into my view model...
public List Stuffs { get; set; }
I json encode it server side and make sure to take care of circular refrences, so it looks like this
[{"id":1,"name":"blah"},{"id":2,"name":"blah2"},{"id":3,"name":"blah3"},{"id":4,"name":"blah4"}]
The problem is, I want to keep my separation of concerns, so how do I get that array into my js file so I can bind it to a select list using knockout? I definitely don't want to do another round trip to the server.
So lets say you have some view that looks like this:
<div> (Some stuff) </div>
<script type="text/javascript">
var initialData = //Your JSON
<script>
And then in your javascript (which you have linked below your view, so that it loads after it), you have something like this:
var data = initialData || {} //Or some other default value, in case initialData wasn't set
This will load in the initialData if it was set, or use nothing (or a default your define) if it wasn't. Loosely coupled.
Of course, more complex data will require you to standardize the strucure, but this is essentially one method that allows you to pull in data from the razor generated View without tightly coupling it to your javascript file.
Does your Javascript file contain a view model in the form of an instantiable function, e.g. something like:
function MasterVM(data)
or an object literal, e.g.
var masterVM = { ...
? I tend to go for instantiable view models (partly because they chain down through a hierarchy of view models using the mapping plugin - the top level one builds its children) and that being the case I think it's nice for the Razor view to instantiate the view model with the JSON rendered from the MVC view model, e.g.:
var masterVM = new MasterVM(#(Html.Raw(JsonConvert.SerializeObject(Model.ProductViewModel))));
Or even have the Knockout view model "owned" by a revealing module and initialise it like:
productModule.init(#(Html.Raw(JsonConvert.SerializeObject(Model.ProductViewModel))));
Then productModule is also responsible for other things like mediating between your view model(s) and the server, watching for dirty state, etc.
Also, doing another round trip to the server is not necessarily bad if you are sourcing a massive set of reusable options which you'd like the browser to cache. If you are, you might want to have an MVC controller which emits a big object literal containing all of your commonly used options, which you can then use as the "options" property across multiple selects. But if your options are specific to the particular view model, then I guess they have to be part of your view model.

Refreshing Partial View in MVC 3

I have a partial view that I have included on my _Layout.cshtml. It simply has a javascript function that changes an image based on the state of my system. I don't need to reload any data, I don't need to go to the code of the controller for anything, I simply need to reload that partial view.
I tried many of the examples that I found here but couldn't get any of them to work. I felt as if they were too complex for what I was doing anyway. Any guidance would be appreciated.
Thanks,
Steve
If the partial is loaded into the layout directly then there's no straightforward way to refresh it, because it's basically a part of the complete rendered page.
Your best bet is to render the partial using $.load or whatever equivalent you have available by hitting a controller method and rendering the result into a container (like a div). You would have to do this within a script that is loaded with the layout itself, by observing document.ready or something like that. Once you have that in place then it's trivial to keep reloading or refreshing the contents by hitting the controller method as many times as you need. For example in jQuery:
$(document).ready(function () {
RefreshPartial();
window.setInterval(RefreshPartial, 10000);
});
function RefreshPartial() {
$('#container').load('/some/controller/endpoint', {parameters});
}
This will call the controller method, and set the inner contents of the element identified with #container. You can call RefreshPartial as many times as you want.
Partial views only exist on the server. The only way to "refresh" the partial is to go back to the server to get it again.
Obviously, you must be doing something in the partial that needs refreshing. Whatever that is, should be callable from javascript to do the refresh.

Resources