Use MVVM Light's Messenger to Pass Values Between View Model - c#

Could someone be so kind as to explain MVVM Light's Messenger for me? I was reading a post on StackOverflow here: MVVM pass values between view models trying to get this. The documentation on MVVM Light's not that great at this point so I'm completely unsure where to go.
Say I have two ViewModels and a ViewModelLocator. I want to be able to pass parameters between all three without issue. How would I go about doing this with the messenger? Is it capable of that?
Edit: Here's my new implementation. As of now, it looks as if MessengerInstance doesn't call for a token. I'm terribly confused.
In the first ViewModel:
MessengerInstance.Send<XDocument>(SelectedDocument);
And in the second:
MessengerInstance.Register<XDocument>(this, xdoc => CopySettings(xdoc));
Could be completely wrong. Haven't gotten a chance to test it, but visual studio gets less angry with me when I do it this way. Also the MessengerInstance does register before the Message is sent.

Say I have two ViewModels and a ViewModelLocator. I want to be able to pass parameters between all three without issue. How would I go about doing this with the messenger? Is it capable of that?
That's exactly what it's for, yes.
To send a message:
MessengerInstance.Send(payload, token);
To receive a message:
MessengerInstance.Register<PayloadType>(
this, token, payload => SomeAction(payload));
There are many overloads, so without knowing exactly what you're trying to accomplish via the messenger, I won't go into all of them, but the above should cover the simple case of wanting to send and receive a message with a payload.
Note that "token" can be really anything that identifies the message. While a string is often used for this, I prefer to use an enum because it's a little safer and enables intellisense, "find usages", etc.
For example:
public enum MessengerToken
{
BrushChanged,
WidthChanged,
HeightChanged
}
Then your send/receive would be something like:
// sending view model
MessengerInstance.Send(Brushes.Red, MessengerToken.BrushChanged);
// receiving view model
// put this line in the constructor
MessengerInstance.Register<Brush>(this, token, brush => ChangeColor(brush));
public void ChangeColor(Brush brush)
{
Brush = brush;
}
[EDIT] URL to devuxer's comment below changed to:
http://blog.galasoft.ch/posts/2009/09/mvvm-light-toolkit-messenger-v2/

Related

Can Model communicate directly to the Data Access Layer?

Sorry if im asking the question wrong but here is an example:
public class Person : BaseModel {
// somne properties like username, password, isLoggedIn
public Person(SomeDataService dataService){...}
public bool Login(){
var result = dataService.TryToLogin(this.username, this.password);
// do some stuff with result
}
}
Some people says it is acceptable but some them says not, so I don't know what is right.
You are legitimate to use any kind of code that works for you, MVVM is just a convention that should help you to code better and quicker, but if it doesn't work for you and there is no 3rd party (like your employer) that enforces this requests you are free to do whatever works the best for you.
Speaking of MVVM, this class above should be a Model, and if you want to respect the MVVM convention you can't do what you did, it should contain just plain properties. But as I said above someone must choose whether he wants to use MVVM at all, so if you haven't decided to stick to the MVVM convention you can use this code, just count on that it may be a bit confusing if you need someone else to work on that code too.

Catel InterestedIn OnViewModelCommandExecuted check which command executed

I use the Catel 4.3.0 framework.
I've decorated one of my ViewModels with
[InterestedIn(typeof(AddSupplierWindowViewModel))]
and added
protected override void OnViewModelCommandExecuted(IViewModel viewModel,
ICatelCommand command, object commandParameter)
This event fires correctly.
In the AddSupplierWindowViewModel I've multiple commands, but only the CmdAddSupplier is of interest to this viewmodel.
So I want to check if this command is fired, but I can't figure out how to test for it.
I expect something like
command.Name == "CmdAddSupplier"
but I can't find something like this.
Could someone provide an example of how to test for this.
Kind regards
Jeroen
We recommend to use CommandContainers instead of view models to host commands that span more than 1 view model. The InterestedIn communication will probably (most likely) be removed from Catel in v5.
Some good examples can be found in the Orchestra repository.
If you really want to keep using the InterestedIn (which is actually a shortcut for setting up services to take care of the communication between the view models), you'll need to figure out how to retrieve the instance (you only get an instance of a command) to a command name. For example, you could use the Tag property on the command.

Windows Phone 8 MVVM light navigation with non string parameter

I'm am new to the .NET/c# realm and I am trying to develop a Windows Phone 8 application.
I have several pages showing lists of Objects(ListPage). All of these pages will have a filter capability, using a commom FilterPage.
What I need is to pass an object from the ListPage to the FilterPage.
I want to use MVVM (MVVM light templates). I've managed to implement almost everything using the Messaging framework. I'm using a FilterMessage that takes the object to be passed in its constructor.
The ListPage and the FilterViewModel listen to this message. The ListPage will navigate to the FilterPage and The FilterViewModel will take the Object from the message.
The ListPage is notified correctly but the FilterViewModel is not notified because the FilterViewModel is created only after the FilterPage is first shown.
Is it possible to initialize the FilterViewModel by App start?
If you think that this is not the way to go please tell me why:)
Thanks in advance.
What I do in this scenario is I'm adding the instance you want to pass around to the other page into the Session object you have under PhoneApplicationService.Current.State.
On the other side after you complete navigation you can extract the instance, and you should remove it from the State.
Pay attention that if your application goes into the background when you have instances inside the State, WP will try to serialize them.
I managed to make it work by creating the FilterViewModel instance in the ViewModelLocator constructor.I'm not sure that this is the best way to do it. Hopefully someone with more experience will share with us his thoughts.
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<FilterViewModel>();
ServiceLocator.Current.GetInstance<FilterViewModel>();
}

Should I put this function in View (code-behind) or in ViewModel?

I am creating a simple WPF Application. I've a function OpenFile:
private void OpenFile(string fileName)
{
if(!File.Exists(Helper.GetPath(fileName)))
{
MessageBox.Show("Error opening file");
}
else
{
//Code to handle file opening
}
}
Ideally where should this function be present? I feel it should be in .xaml.cs because it accesses a MessageBox which comes in the View part. But it also calls my Helper, which is in the model. So I also think it can be in the ViewModel. What is the advantage of having this in the View or in the ViewModel? Can someone help me with some pointers?
Thanks.
One of the advantages of placing it in the view model would be testability. You could write a unit test that checks that the message box is only displayed if the file exists for example (more accurately it would be an integration test if you are hitting the file system).
However, because you are using a message box directly, your test would never complete on a build server because the machine would be waiting for input from the user whilst the message box is displayed.
Therefore, I would work against an abstraction in your view model, so that you can mock the message box during tests.
This function must be in the ViewModel. You need to create an operation in your view for showing the error message and call this method instead of MessageBox.Show. Showing the message box needs to be done in the View.
Generally you should avoid implementing any business logic inside the View such as validating or handling a file.
If you're using Microsoft Prism you can use the IInteractionRequest interface to have the view create the MessageBox, but actually pass back the necessary response to the view-model.
If you are not using Microsoft Prism, then look at how this part works and either simulate it or use a framework that does something similar.
Basically, that code should go on your view-model for testability, but replace the line where you explicitly call the MessageBox and use the IInteractionRequest mentioned instead.
Here is the documentation pertinent to the scenario you're looking to implement: Chapter 6: Advanced MVVM Scenarios. Look at the section stated User Interaction Patterns.

MVC 3 - How is this ever going to work?

I have made this post over a year ago, and I think it makes sense to update it as it's getting quite a few views.
I'm either missing something out or Microsoft has really messed up MVC. I worked on Java MVC projects and they were clean and simple. This is however a complete mess IMO. Examples online such as NerdDinner and projects discussed on ASP.Net are too basic, hence why they "simply" work. Excuse if this sounds negative, but this is my experience so far.
I have a repository and a service that speaks to the repository. Controllers call service.
My data layer is NOT persistence independent, as the classes were generated by SQL metal. Because of this I have a lot of unnecessary functionality. Ideally I'd like to have POCO, but I didn't find a good way to achieve this yet.
*Update: Of course Microsoft hasn't messed anything up - I did. I didn't fully understand the tools that were at my disposal. The major flaw in what I have done, was that I have chosen a wrong technology for persisting my entities. LINQ to SQL works well in stateful applications as the data context can be easily tracked. However, this is not a case in stateless context. What would be the right choice? Entity Framework code first or code only work pretty well, but what's more importantly, is that it shouldn't matter. MVC, or front end applications must should not aware of how data is persisted. *
When creating entites I can use object binding:
[HttpPost]
public ActionResult Create(Customer c)
{
// Persistance logic and return view
}
This works great, MVC does some binding behind the scene and everything is "jolly good".
It wasn't "Jolly Good". Customer was a domain model, and what was worse, it was dependent on persistence medium, because it was generated by SQL metal. What I would do now, is design my domain model, which would be independent of data storage or presentation layers. I would then create view model from my domain model and use that instead.
As soon as I'd like to do some more complex, e.g. - save Order which is linked to the customer everything seems to break:
[HttpPost]
public ActionResult Create(Order o)
{
// Persistance logic and return view
}
To persist an order I need Customer or at least CustomerId. CustomerId was present in the view, but by the time it has got to Create method, it has lost CustomerId. I don't fancy sitting around debugging MVC code as I won't be able to change it in a hosting envrionment either way.
Ok, a bit of moaning here, sorry. What I would do now, is create a view model called NewOrder, or SaveOrder, or EditOrder depending on what I'm trying to achieve. This view model would contain all the properties that I'm interested in. Out-of-the-box auto binding, as the name implies, will bind submitted values and nothing will be lost. If I want custom behaviour, then I can implement my own "binding" and it will do the job.
Alternative is to use FormCollection:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
// Here I use the "magic" UpdateModel method which sometimes works and sometimes doesn't, at least for LINQ Entities.
}
This is used in books and tutorials, but I don't see a point in a method which has an alternative: TryUpdateModel - if this crashes or model is invalid, it attempts to update it either way. How can you be certain that this is going to work?
Autobinding with view models will work the most of the time. If it doesn't, then you can override it. How do you know it will always work? You unit test it and you sleep well.
Another approach that I have tried is using ViewModel - wrapper objects with validation rules. This sounds like a good idea, except that I don't want to add annotations to Entity classes. This approach is great for displaying the data, but what do you do when it comes to writing data?
[HttpPost]
public ActionResult Create(CustomViewWrapper submittedObject)
{
// Here I'd have to manually iterate through fields in submittedObject, map it to my Entities, and then, eventually, submit it to the service/repository.
}
** View model is a good way forward. There would have to be some mapping code from view model to the domain model, which can then be passed to the relevant service. This is not a correct way, but it's one way of doing it. Auto mapping tools are you best friends and you should find the one that suits your requirements, otherwise you'll be writing tons of boilerplate code.**
Am I missing something out or is this the way Microsoft MVC3 should work? I don't see how this is simplifying things, especiialy in comparisson to Java MVC.
I'm sorry if this sounds negative, but this has been my experience so far. I appreciate the fact that the framework is constantly being improved, methods like UpdateModel get introduced, but where is the documentation? Maybe it's time to stop and think for a little bit? I prefer my code to be consistent throughout, but with what I have seen so far, I have no confidence whatsoever that this is a right way forward.
I love the framework. There is so much to learn and it's not a lot more exciting then it has ever been. Should probably make another post regarding web forms. I hope this is helpful.
1) For the case of saving an order, and not having CustomerId present. If Order has a CustomerId property on it, and you have a stongly typed view, then you can persist this back to your controller action by adding
#Html.HiddenFor(model => model.CustomerId)
Doing this will have the default model binder populate things for you.
2) With respect to using a view model, I would recommend that approach. If you utilize something like AutoMapper you can take some of the pain out of redundant mapping scenarios. If you use something like Fluent Validation then you can separate validation concerns nicely.
Here's a good link on a general ASP.NET MVC implementation approach.
I don't think your issue is with asp.net MVC but with all the pieces You Choose to use together.
You want it raw and simple?
Use POCOs all around, and implement the repository where you need it.
I haven't used Java MVC, but it'd make the whole question look less like a rant if you include how you solved the particular problem in there.
Let's clear some misconceptions or maybe miscommunication:
You can pass complex objects through a post to the view. But you only want to do so if it makes sense, see next bullet
The sample you picked there rings some alarms. Accepting Customer data or CustomerID for an order and not checking authorization can be a Big security hole. The same could be said for an Order depending on what you are accepting/allowing. This is a Huge case for the use of ViewModels, regardless of POCOs, LINQ, Asp.net MVC or Java MVC.
You can pass simple values not being showed through a post to the view. It's done with hidden fields (which asp.net MVC supports very simply to use the model value), and in some scenarios it generates the hidden fields for you.
You are in no way forced to use linq2sql with Asp.net MVC. If you find it lacking for how you intend to use it, move away from it. Note I love linq2sql, but how it is tied to your view of what you can do with asp.net mvc is weird.
" I worked on Java MVC projects and they were clean and simple". Working on a project is not the same as designing the project yourself. Design skills does affect what you get out of anything. Not saying is your case, but just wanted to point that out given the lack of specifics on what you're missing from Java MVC.
"My data layer is NOT persistence independent, as the classes were generated by SQL metal. Because of this I have a lot of unnecessary functionality. Ideally I'd like to have POCO, but I didn't find a good way to achieve this yet". You picked the wrong technology, linq2sql is Not meant to fit that requirement. It haven't been a problem in the projects I've used it, but everything is designed in such a way that way less tied to its specifics than you seem to be. That said, just move to something else. btw, You should have shared what you used with Java MVC.
"CustomerId was present in the view, but by the time it has got to Create method, it has lost CustomerId." If the property is in Order, You can bet your code has the bug. Now, that'd have been a totally different Real question, why it isn't using the CustomerId / such question would come with: your Customer class, the View, what you are passing to the View ... answers would include, but not be limited to: inspect the HTML source in the browser to see what value you are really posting with the source (alternatively use fiddler to see the same), make sure that CustomerId really has the value when you pass it to the View.
You said: ""magic" UpdateModel method which sometimes works and sometimes doesn't". It's not magic, you can see what it does and certainly find information on it. Something is off in the information you are posting, my bet is non optional fields or wrong values for information that's parsed ... views support adding validations for that. Without the validations, this can be lacking.
You said in a comment: "After UpdateModel is called, i can't explicitly set the CustomerId, I'll have to retrieve a customer object and then assign it to the order, which seems like an overhead as all that I need is CustomerId" ... you are accepting a CustomerId that is user input (even if it is a hidden field), you really want to Validate that input. Additionally you are contradicting yourself, you claim to just need CustomerId, but then you say you need the full Customer Object related to the order bound. Which is it, if you are only binding the CustomerId, you still need to go get that Customer and assign it to the property. There is no magic besides the scenes ...
Also in a comment: "Update model is something I'm avoiding completely now as I don't know how it will behave with LINQ entities. In the view model class I have created constructor that converts LINQ entity to my view model. This decreased amount of code in controller, but still doesn't feel right". Reason to use ViewModel (or EditModel) is not because it is linq2sql ... it is because, among many other reasons, you are exposing a model that allows to manipulate way beyond what you actually want to allow the user to modify. Exposing the raw model, if it has fields the user shouldn't be allowed to modify, is the real issue.
If your view is correctly defined then you can easily do this >
[HttpPost]
public ActionResult Create(Order o, int CustomerId)
{
//you got the id, life back to jolly good (hopefully)
// Persistance logic and return view
}
EDIT:
as attadieni mentioned, by correct view I meant you have something like this inside the form tag >
#Html.HiddenFor(model => model.CustomerId)
ASP.NET MVC will automatically bind to the respective parameters.
I must be missing the problem.
You have a controller Order with an Action of Create just like you said:
public class OrderController()
{
[HttpGet]
public ViewResult Create()
{
var vm = new OrderCreateViewModel {
Customers = _customersService.All(),
//An option, not the only solution; for simplicities sake
CustomerId = *some value which you might already know*;
//If you know it set it, if you don't use another scheme.
}
return View(vm);
}
[HttpPost]
public ActionResult Create(OrderCreateViewModel model)
{
// Persistance logic and return view
}
}
The Create action posts back a view model of type OrderCreateViewModel that looks like such.
public class OrderCreateViewModel
{
// a whole bunch of order properties....
public Cart OrderItems { get; set; }
public int CustomerId { get; set; }
// Different options
public List<Customer> Customers { get; set; } // An option
public string CustomerName { get; set; } // An option to use as a client side search
}
Your view has a dropdown list of customers which you could add as a property to the viewmodel or a textbox which you wire up to to searching on the server side via JQuery where you could set a hidden field of CustomerId when a match is made, however you decide to do it. And if you already know the customerId ahead of time (which some of the other posts seems to imply) then just set it in the viewmodel and bypass all the above.
You have all of your order data. You have the customer Id of the customer attached to this order. You're good to go.
"To persist an order I need Customer or at least CustomerId. CustomerId was present in the view, but by the time it has got to Create method, it has lost CustomerId."
What? Why? If CustomerId was in the view, set, and posted back, it's in the model for the HttpPost Create method which is exactly where you need it. What do you mean it's being lost?
The ViewModel gets mapped to a Model object of type order. As suggested, using AutoMapper is helpful...
[HttpPost]
public ActionResult Create(OrderCreateViewModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// Persistance logic and return view
var orderToCreate = new Order();
//Build an AutoMapper map
Mapper.CreateMap<OrderCreateViewModel, Order>();
//Map View Model to object(s)
Mapper.Map(model, orderToCreate);
//Other specialized mapping and logic
_orderService.Create(orderToCreate);
//Handle outcome. return view, spit out error, etc.
}
It's not a necessity, you can map it manually, but it just makes things easier.
And you're set. If you don't want to use data annotations for validation, fine, do it in the service layer, use the fluent validation library mentioned, whatever you choose. Once you call the Create() method of your service layer with all the data, you're good to go.
Where's the disconnect? What are we missing?
ataddeini's answer is correct, I'm just trying to show a bit more code. Upvote ataddeini
If the Customer Id is already in the Order model (in this example) it should be available without extending the method signature. If you view the source on the rendered view, is the customer id correctly emitted in a hidden field within the form? Are you using the [Bind] attribute on the Order model class and inadvertently preventing the Customer Id from being populated?
I would think the Order table would include a CustomerID field, if so, the only problem is maybe you are not including any control in the view to keep that value, then is lost.
Try to follow this example.
1) GET action before sending to the View, let's say you assign the CustomerID at this point.
public ActionResult Create()
{
var o = new Order();
o.CustomerID = User.Identity.Name; // or any other wher you store the customerID
return View(o);
}
2) The View, if you don't use any control for the CustomerID, like textbox, combobox, etc, you must use a hidden field to keep the value.
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.CustomerID)
<label>Requested Date:</label>
#Html.TextBoxFor(m => m.DateRequested)
...
}
3) Finally, the POST action to get and persist the order. In here, as CustomerID was kept in the hidden value, the Model Binder will automatically put all the Form values into the Order object o, then you just need to use CRUD methods and persist it.
[HttpPost]
public ActionResult Create(Order o)
{
return View();
}
Can be two approaches for this, one to implicit save all Model values even if not used in the View, and the other is to keep only those values used. I think MVC is doing the right thing to follow the later, avoid unnecessary keep a lot of junk for bigger models, when the only think is, to name one, a CustomerName, somehow it can give you control on what data to keep through the whole cycle action-view-action and save memory.
For more complex scenarios, where not all fields are in the same model, you need to use ViewModels. For example for mater-detail scenarios you would create a OrderViewModel that has two properties: Order o, and IEnumerable< OrderDetail > od, but again, you will need explicit use the values in the View, or use hidden fields.
In recent releases now you can use POCO classes and Code-First that makes all cleaner and easier, You may want to try EF4 + CTP5.
if you are using services (aka; service layer, business facade), to process lets say the OrderModel, you can extract an Interface, and get your ViewModel/DTO to implement it, so that you can pass back the ViewModel/DTO to the service.
If you are using Repositories to directly manage the data (without a servie layer) in the controller, then you can do it the good old way of Loading the object from a repository and then doing an UpdateModel on it.
[HttpPost]
public ActionResult Create(string customerCode, int customerId, Order order)
{
var cust = _customerRepository.Get(customerId);
cust.AddOrder(order);//this should carry the customerId to the order.CustomerId
}
Also, URLs might help a bit where it makes sense, I mean you can add the customer identifier in the url to create the order for.
UpdateModel should work, if your FormCollection has values for non-nullable properties and they are empty/null in the FormCollection, then UpdateModel should fail.

Categories

Resources