How do I rebind the knockout viewmodel when the page is loaded in as a partial via ajax? - 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"));

Related

Clarification needed in using Ajax forms and Partial Page

I am newbie to MVC and Web App.
Recently I have went through the article
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
It uses the Ajax Form, to do the partial update towards a particular region alone..
But I have a doubt in that example...
I have seen the partial Page inside the Div with Id "AllTweets"....
<div id="AllTweets">
#Html.Partial("_AllTweets", Model) ***** (XXX)
</div>
And also in the controller action,
try
{
viewModel.Tweets.Add(viewModel.Tweet);
return PartialView("_AllTweets", viewModel); **** (YYYYY)
}
Now my question is,
They are returning the partial view along with the data from the action in the controller.
Whatever the data returned from the controller, the engine will place that data, inside the target div with id "AllTweets"...
But still, why I have to have the statement, #Html.Partial("_AllTweets", Model) inside the Div, since already I am returning the data from the controller...
And also in some of the examples, i have seen the same kind of the code..
But, even if I have removed the code "#Html.Partial("_AllTweets", Model)" inside the div, the code still works fine, and without any problem and i can able to post the data to the action in the controller.
I got totally stuck at this point.
May I kindly know, what is the reason behind it and why so.... So I can understand it more better.
Thanks in advance...
But, even if I have removed the code #Html.Partial("_AllTweets",
Model) inside the div, the code still works fine, and without any
problem and i can able to post the data to the action in the
controller.
Yes it will work fine. The Html.Partial("_AllTweets",Model) renders the partial with the specified model on every page load. After page is loaded, then ajax is used to fill the div with id AllTweets.
Html.Partial("_AllTweets",Model) is usefull when you want to display, for example, already saved tweets from your database to user when the page first loads. And then ajax takes care of later updates.

Update template inside a view rendered from another controller

I am looking for the way to refresh a template inside a view rendered from another controller than the template's controller, I mean:
I got two controllers AdminController & UserController. And two gsps /admin/listUsers & /user/_searchResult.
Then a want to render view listUsers who have inside the template _searchResult and all right.
Now, i want to refresh the template _searchResult, but cant find how. I tryed calling render(view:"/admin/listUsers", template:"/user/_searchResult", model:[searchResult:result])
AdminController.groovy
#Secured(['ROLE_ADMIN'])
def listUsers(){
//...
}
UserController.groovy
#Secured(['ROLE_ADMIN'])
def search(){
//search users for the givven params and send result by chain if there's an action or update a template if it's needed
//in my case this method need to update the template _searchResult
}
#Secured(['ROLE_ADMIN'])
def searchResult(){
//...
[searchResult:result]
}
listUsers.gsp
//...
<formRemote name="searchForm" url="[action:"search", controller:"user"]">
//Some fields for the search
//I need to place here some hidden inputs to send which
//template i want to update or action to redirect
</formRemote>
<g:render template="/user/_searchResult"/>
//...
_searchResult.gsp
//Just itterate and print the search result in a table
I hope I have explained the problem correctly, thanks!
I don't think I entirely understand your question, but I think the source of your confusion is that the way you are naming things doesn't follow regular conventions and you're not using the right tools for the job. Let me explain...
The methods on Controllers are called Actions. They send some data (the Model) to a View to be rendered into HTML. Views can be composed from smaller, reusable fragments called Templates. (sorry if I sound like I'm being condescending here, but I'm just trying to make sure we're all on the same page).
Now, what you've called templateA is actually a View, not a Template. You're correct that templateA (your View) can call templateB to render some markup, but then having the templateB try to call a method on another Controller doesn't make sense. That's not how things flow.
If you have some logic that needs to be executed after you've sent your Model to the View, you want to use a Tag Library (http://grails.org/doc/latest/guide/theWebLayer.html#taglibs).
To summarise, here's a quick recap.
A request should only call one Action, which sends the model to only one view.
If you need to reuse logic between Controllers, move that code to a Service.
If you need to reuse markup between Views, move that markup to a Template.
If you have logic that you want to have executed after you've sent the Model to the View, use a Tag Library.
Hopefully this will point you in the right direction.
--- UPDATE ---
OK, with the real code I can see better what you're trying to achieve. Firstly, as you're using the <g:formRemote> tag, you should have a good read of the docs at http://grails.org/doc/latest/ref/Tags/formRemote.html to understand what it does.
What you will have here is 2 separate requests. The first will be a regular page load by your browser, which is handled by the listUsers() action. Once the page is then finished loading, the user will enter a search term and hit the submit button. This will fire off a second ajax request, which will be handled by the search() action. This action could use the _searchResult.gsp template to render a HTML table to display the search results. When the browser get this, it will insert it into the DOM where you've told it to put it using the "update" attribute of the <g:formRemote> tag.
The important thing here is that from the server's perspective, these are 2 separate requests that are completely independent. They both first call an action, then send a model (a Map containing some data) to a view, which renders/merges the data with HTML and sends it back to the browser.
The difference between the 2 is that the first is a complete page load by the browser, whereas for the second request, the browser only loads a small chunk of HTML (the search results table) and updates the page content without reloading it.
So your code would look more like this...
AdminController.groovy
#Secured(['ROLE_ADMIN'])
def listUsers() {
render(view:"/admin/listUsers")
}
listUsers.gsp
<g:formRemote name="searchForm" update="insertSearchResultsHere"
url="[controller: 'user', action:'search']">
<input name="searchTerm" type="text" />
</g:formRemote>
<div id="insertSearchResultsHere"></div>
UserController.groovy
#Secured(['ROLE_ADMIN'])
def search() {
// use the search term to get a List<User>
render(template: "/user/searchResult", model: [users: users])
}
_searchResult.gsp
<table>
<g:each var="user" in="${users}">
%{-- Iterate through your search results --}%
</g:each>
</table>
I solved it by placing the attribute update and rendering the template alone:
gsp:
<formRemote name="searchForm" url="[action:"search", controller:"user"]" update="divToUpdate">
//Some fields for the search
</formRemote>
<div id="divToUpdate">
<g:render template="/user/_searchResult"/>
</div>
Controller:
def search(){
render(template:"/user/_searchResult", model:[searchResult:result])
}
When i asked this question, i was new on Grails community and i was confused with the use of remoteFunction and tags that use it like remoteForm. But i had this confusion because of i had not read the documentation. So in my case, the solution was search for documentation about how to use remote tags and render. Thanks to #AndrewW for show me the way.

Complex Pages and Data

I am trying to figure out the best way to handle pages in our application like the dashboard, where there are a number of different panes with various bits of data in it.
The main issue is that the controller action becomes unwieldy when the page needs so much data. The client side can be broken up into partial views to make it more manageable, but all the data still needs to passed into the View to be distributed down to the partials. Or does it?
Obviously some of the panels could be loaded dynamically or something like that, but I was looking for the best approach besides loading individual piece of the page from the browser.
Have you considered using Html.Action in your view? You would pass enough data to the main view to enable you to give the required data to each of the child actions. The main action would render the main view which would call actions for each pane. Each action would be responsible for that pane, rendering its own partial view. Additionally, you could call back to each of the child actions directly from the client to update that pane dynamically via AJAX.
Here's an example with some mocked up actions of what your main view might look like.
<div class="left-pane">
#Html.Action("Summary", new { id = Model.ID } )
</div>
<div class="middle-pane">
#Html.Action("PendingItems", new { id = Model.ID, timestamp = DateTime.Now } )
</div>
<div class="right-pane">
#Html.Action("News")
</div>

How to get view model directly in layout?

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.

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