Durandal navigate to a view with model as parameter - viewmodel

I want to navigate to a view html file (from another view's js file) but pass in the model to be used by that view. How can I do this please.
I can generally do this when I am opening the new view in a dialog. In this case, I create the model object (var model = require('viewmodels/modeljsfile), and then creating an instance of this model and accessing the properties (var instance = new model(); instance.property1 = 'Test). I then pass this instance to my modal.
Instead of opening in view html in a modal, I want to redirect to the actual view. How can I do this please?

In the view add a Compose and state the target view/model. Note that both the View/Model can be variables from the parent view.
Be careful however as not all the life cycle events are attached (activator.js)
<div data-bind="compose: { model:someModelProperty, view:someViewProperty }"/>
http://durandaljs.com/documentation/Using-Composition.html

Related

Handling secondary popup controller events from main controller JavaFX

I have a main controller which handles my main.fxml and a second controller which handles my popup.fxml
When a button is pressed from the main controller, the popup windows appears. In the popup window you add players. The players are added by textfield to an array and must be sent back to main controller. I have a button called "btnApply" in my popup controller, when that is pressed I want to close the popup window and handle the array from my main controller class. I only want my main controller class to be aware of the popup.
This is how I am creating a popup from main controller:
button.setOnAction(e -> newWindow());
public void newWindow(){
try{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("popup.fxml"));
Parent popupRoot = fxmlLoader.load();
Stage playerStage = new Stage();
playerStage.setTitle("Player");
playerStage.setScene(new Scene(popupRoot, 720, 600));
playerStage.show();
}catch(Exception e) {
e.printStackTrace();
}
}
Now the question is how to I get the event or the object. When I created the popup window without using FXML (created the GUI manually), it was easy because I just made an object of the Class Popup and had a getButton() and getArray(). In my main controller class I had a Popup popup = new Popup(); then I had a method where I handle the button from my popup class popup.getButton().setOnAction(e -> addPlayers());
But this is not possible using fxml. I cant seem to get the object that is running. If I were to create a Popup popup I will just get a new event not the one that is being ran.
The way to do this most similar to your previous approach would be adding the getButton() method to to your controller class and get the controller class from the FXMLLoader:
Parent popupRoot = fxmlLoader.load();
MyController controller = fxmlLoader.<MyController>getController();
controller.getButton()...
Alternatives
However I recommend a different approach to passing the data, since this way you limit yourself to a single button in the popup as the only way to submit the players. I'd rather do this by "notifying" the class creating the popup, i.e:
Implement this interface in the calling class
public interface PlayerContainer {
void addPlayers(Player[] players);
}
and add this to the controller:
private PlayerContainer playerContainer;
public void setPlayerContainer(PlayerContainer playerContainer) {
this.playerContainer = playerContainer;
}
And pass the calling class to the controller directly after loading the popup content:
Parent popupRoot = fxmlLoader.load();
MyController controller = fxmlLoader.<MyController>getController();
controller.setPlayerContainer(this);
and when the user submits the player data, simply call
this.playerContainer.addPlayers(playerData);
in addition to closing the window. Passing a ObservableList<Player> to the controller class instead and adding all players to this list would work too, if you handle changes to the list appropriately in the calling class.
Take a look at jewelsea's answer to "Passing Parameters JavaFX FXML". This lists some alternative ways to can pass objects to the controller of the fxml. The Setting a Controller on the FXMLLoader approach could be easy to implement, e.g. if you use a inner class of the calling class as the controller class. This way it's harder to reuse the popup than with the approach described above however...

Update the view although the model hasn't changed

My app updates the view in response to events dispatched by the model. But what if the model hasn't changed, but I still need to update the view. For example, I've closed and reopened a pop-up. The data to be displayed hasn't changed but the pop-up mediator and the view have to be recreated. My current solution is to force initialization in the mediator's onRegister() method like this:
// Inside of PopUpMediator.as
[Inject]
public var popUpModel:IPopUpModel;
[Inject]
public var popUpView:PopUpView;
override public function onRegister()
{
// Force initialization if the model hasn't changed
popUpView.foo = popUpModel.foo;
// Event based initialization
addContextListener(PopUpModelEvent_foo.CHANGE, foo_changeHandler);
}
Injecting models into mediators isn't a good idea, so I'm wondering What is the best way to init the view when its model hasn't changed?
Well,
I supose you have View1 where you have popup button.
View2 is your popus.
so when View1 button is clicked, you dispatch an event from main mediator that goes to popupCommand where you add popup to contextView, or where you remove it.
You can also have one state inside a model, that will say popupVisible and when you change that property you dispatch a event that is listened in the main mediator and that adds or removes the popup. In that case command would alter the model property instead of adding popup directly to contextView.
Third way is to add popup manually inside the view, and since the stage is being listened to by robotlegs, popup will be mediated automatically.
I've decided to add an event called PopUpViewInitEvent. A command will check if the model was updated while the pop-up was closed. If not it will reinitialize the view by dispatching the PopUpViewInitEvent. The event will contain all the data required to initialize the view. This way I won't have to inject models into my mediator.
[Inject]
public var popUpView:PopUpView;
override public function onRegister()
{
// Batch initialization
addContextListener(PopUpViewInitEvent.INIT, batchInit);
// Gradual initialization
addContextListener(PopUpModelEvent_foo.CHANGE, foo_changeHandler);
addContextListener(PopUpModelEvent_bar.CHANGE, bar_changeHandler);
}
protected function batchInit(event:PopUpViewInitEvent)
{
popUpView.foo = event.foo;
popUpView.bar = event.bar;
}

MVC how to include a view that does not have layout info

I'm trying to reference a view, but do not want all the header and footer that comes with the view because the viewstart references layout page. When I have a popup, it also shows the menu items in the header. Is there a way not to include the layout.cshtml?
Layouts can be specified directly in the view or based on the caller.
For example if your ActionMethod returns like this:
return View();
The view will be rendered with the layout. However if the ActionMethod returns like this:
return PartialView();
Then the rendered view will not have a layout.
However, this can be overridden in the view itself. In your view, if ViewBag.Layout is null the layout will not be included. Inversely, if ViewBag.Layout has a value that layout will be used, reguardless of how the view is called. For this reason, most views do not set ViewBag.Layout directly, and leave it up the the caller to specify the intent.
Hope his helps.
All you have to do is explicitly set layout to null.
#{ Layout = null; }
Put this in the header of the view
#{ Layout = null; }
Or something like that

Is it possible to add a view model on the _layout.cshtml?

The scenario is that I want to populate the navigation bar, the menu, with Mvc.Sitemap.
How should I achieve this?
It feels strange to add a View Model onto the layout page. And that may cause a view to have more than one View Models.
can any one help? Thank you.
Update: ----------
I have Home/_Menu as a partial view which uses MenuViewModel. But how can I include that View in _layout?
I cannot simply use #Html.Partial("_Menu") inside my _Layout.cshtml because I need to specify the controller and action where the view model is built. What is the correct way to do this?
And if I do #Html.RenderAction("_Menu", "Home"), I get a Object reference not set to an instance of an object. error on the Model.
You should not have a model in your Layout, because then every view that you call from there by default will have this model. Instead you should create a Menu view with the model, and when you call it pass a new MenuModel to it as a model.
Edit:
You can have a class that will pull data out of where you store your menu values. Then you call your partial like this:
#Html.Partial("_Menu_", menuobject.Root)
And the class:
partial class menuobject
{
public static menuobject Root
{
// MenuRoots are all roots that have ID -1 - which will be the root
return MenuRoots.Single(x => x.Something == "Topnavi"); // this will return the root above all your menus
}
}
Than in your view you go foreach() on each level of menus to populate them.

Inject a statement from the Controller

I'm writing an MVC 3 app and I have tried to code a control in the Controller (due to permissions, different menu items will be visible for different users) and use the object in the Razor page. For example, in the Controller I do something like:
public ActionResult Index()
{
var menu = "#(Html.Telerik().Menu().Name("menu").Items("menus => { menus.Add().Text("Home").Action("Index", "Home"); menus.Add().Text("Deliveries").Action("Index", "Delivery"); }))";
var model = new MenuModel()
{
Menu = menu
};
return View(model);
}
And in the View I try to render the Menu using #Model.Menu but I just get the string value rather than an actual menu. Is what I'm trying to do possible?
Extend the HtmlHelper class and use the newly created method to render your menu in the View:
Helper:
public static string RenderMenu(this HtmlHelper html)
{
var menu = new StringBuilder();
/* ... menu rendering logic ... */
return menu.ToString();
}
View:
#Html.RenderMenu();
Nevertheless, it is fine to put this logic in the view. Using the HtmlHelper extension just separates/cleans the code.
I wouldn't want to do it that way even if it were possible!
You should decouple your controller and view more than you are currently doing.
The controller should only pass data the view requires. If the view needs a menu with different menu items then use the controller to decide what menu items the view should have then add them to a list object and pass that list to the view. The view will then build a menu based on the list of menu items.
Also when I say "menu items" I don't mean markup! I mean create a new MenuItemViewModel object to persist your data between your controller and your view e.g pseudo code:
public class MenuItemViewModel { string url, string text }
List<MenuItemViewModel> menuitems ...
return View(menuitems)
Why would you want to do this? This is breaking the separation of concerns in MVC - your controller shouldn't worry about how the menu is displayed, just getting the right data to the view for display.
If you want to do security trimming, don't pass in a builder string. There are other methods available.
You could try the MVC SiteMap provider which can handle security trimming against the [Authorize] controller attributes (bit of work to learn and setup, but great once its there).
Pass in your own collection of flags or pre-build menu items, like what Greg suggested.
Make a HtmlHelper extension, something like 'IsAuthorized()' that will check against the controller authorize attributes. Here's a gist of one I used to use before switching to the MVC Sitemap.
With the html helper, you can do this:
#(Html.Telerik().Menu()
.Name("Menu")
.Items(m =>
{
#* Publicly Accessible Controller *#
m.Add()
.Text("Home").Url(Url.Action("Index", "Home"));
#* Secure Controller *#
if (Html.IsAuthorized<MyProject.Controllers.SecureController>(c => c.Index()))
{
//m.Add()....
}
.....

Resources