Search Results

Search found 895 results on 36 pages for 'viewmodel'.

Page 14/36 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • MVVM in Task-It

    As I'm gearing up to write a post about dynamic XAP loading with MEF, I'd like to first talk a bit about MVVM, the Model-View-ViewModel pattern, as I will be leveraging this pattern in my future posts. Download Source Code Why MVVM? Your first question may be, "why do I need this pattern? I've been using a code-behind approach for years and it works fine." Well, you really don't have to make the switch to MVVM, but let me first explain some of the benefits I see for doing so. MVVM Benefits Testability - This is the one you'll probably hear the most about when it comes to MVVM. Moving most of the code from your code-behind to a separate view model class means you can now write unit tests against the view model without any knowledge of a view (UserControl). Multiple UIs - Let's just say that you've created a killer app, it's running in the browser, and maybe you've even made it run out-of-browser. Now what if your boss comes to you and says, "I heard about this new Windows Phone 7 device that is coming out later this year. Can you start porting the app to that device?". Well, now you have to create a new UI (UserControls, etc.) because you have a lot less screen real estate to work with. So what do you do, copy all of your existing UserControls, paste them, rename them, and then start changing the code? Hmm, that doesn't sound so good. But wait, if most of the code that makes your browser-based app tick lives in view model classes, now you can create new view (UserControls) for Windows Phone 7 that reference the same view model classes as your browser-based app. Page state - In Silverlight you're at some point going to be faced with the same issue you dealt with for years in ASP.NET, maintaining page state. Let's say a user hits your Products page, does some stuff (filters record, etc.), then leaves the page and comes back later. It would be best if the Products page was in the same state as when they left it right? Well, if you've thrown away your view (UserControl or Page) and moved off to another part of the UI, when you come back to Products you're probably going to re-instantiate your view...which will put it right back in the state it was when it started. Hmm, not good. Well, with a little help from MEF you can store the state in your view model class, MEF will keep that view model instance hanging around in memory, and then you simply rebind your view to the view model class. I made that sound easy, but it's actually a bit of work to properly store and restore the state. At least it can be done though, which will make your users a lot happier! I'll talk more about this in an upcoming blog post. No event handlers? Another nice thing about MVVM is that you can bind your UserControls to the view model, which may eliminate the need for event handlers in your code-behind. So instead of having a Click handler on a Button (or RadMenuItem), for example, you can now bind your control's Command property to a DelegateCommand in your view model (I'll talk more about Commands in an upcoming post). Instead of having a SelectionChanged event handler on your RadGridView you can now bind its SelectedItem property to a property in your view model, and each time the user clicks a row, the view model property's setter will be called. Now through the magic of binding we can eliminate the need for traditional code-behind based event handlers on our user interface controls, and the best thing is that the view model knows about everything that's going on...which means we can test things without a user interface. The brains of the operation So what we're seeing here is that the view is now just a dumb layer that binds to the view model, and that the view model is in control of just about everything, like what happens when a RadGridView row is selected, or when a RadComboBoxItem is selected, or when a RadMenuItem is clicked. It is also responsible for loading data when the page is hit, as well as kicking off data inserts, updates and deletions. Once again, all of this stuff can be tested without the need for a user interface. If the test works, then it'll work regardless of whether the user is hitting the browser-based version of your app, or the Windows Phone 7 version. Nice! The database Before running the code for this app you will need to create the database. First, create a database called MVVMProject in SQL Server, then run MVVMProject.sql in the MVVMProject/Database directory of your downloaded .zip file. This should give you a Task table with 3 records in it. When you fire up the solution you will also need to update the connection string in web.config to point to your database instead of IBM12\SQLSERVER2008. The code One note about this code is that it runs against the latest Silverlight 4 RC and WCF RIA Services code. Please see my first blog post about updating to the RC bits. Beta to RC - Part 1 At the top of this post is a link to a sample project that demonstrates a sample application with a Tasks page that uses the MVVM pattern. This is a simplified version of how I have implemented the Tasks page in the Task-It application. Youll notice that Tasks.xaml has very little code to it. Just a TextBlock that displays the page title and a ContentControl. <StackPanel>     <TextBlock Text="Tasks" Style="{StaticResource PageTitleStyle}"/>     <Rectangle Style="{StaticResource StandardSpacerStyle}"/>     <ContentControl x:Name="ContentControl1"/> </StackPanel> In List.xaml we have a RadGridView. Notice that the ItemsSource is bound to a property in the view model class call Tasks, SelectedItem is bound to a property in the view model called SelectedItem, and IsBusy is bound to a property in the view model called IsLoading. <Grid>     <telerikGridView:RadGridView ItemsSource="{Binding Tasks}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"                                  IsBusy="{Binding IsLoading}" AutoGenerateColumns="False" IsReadOnly="True" RowIndicatorVisibility="Collapsed"                IsFilteringAllowed="False" ShowGroupPanel="False">         <telerikGridView:RadGridView.Columns>             <telerikGridView:GridViewDataColumn Header="Name" DataMemberBinding="{Binding Name}" Width="3*"/>             <telerikGridView:GridViewDataColumn Header="Due" DataMemberBinding="{Binding DueDate}" DataFormatString="{}{0:d}" Width="*"/>         </telerikGridView:RadGridView.Columns>     </telerikGridView:RadGridView> </Grid> In Details.xaml we have a Save button that is bound to a property called SaveCommand in our view model. We also have a simple form (Im using a couple of controls here from Silverlight.FX for the form layout, FormPanel and Label simply because they make for a clean XAML layout). Notice that the FormPanel is also bound to the SelectedItem in the view model (the same one that the RadGridView is). The two form controls, the TextBox and RadDatePicker) are bound to the SelectedItem's Name and DueDate properties. These are properties of the Task object that WCF RIA Services creates. <StackPanel>     <Button Content="Save" Command="{Binding SaveCommand}" HorizontalAlignment="Left"/>     <Rectangle Style="{StaticResource StandardSpacerStyle}"/>     <fxui:FormPanel DataContext="{Binding SelectedItem}" Style="{StaticResource FormContainerStyle}">         <fxui:Label Text="Name:"/>         <TextBox Text="{Binding Name, Mode=TwoWay}"/>         <fxui:Label Text="Due:"/>         <telerikInput:RadDatePicker SelectedDate="{Binding DueDate, Mode=TwoWay}"/>     </fxui:FormPanel> </StackPanel> In the code-behind of the Tasks control, Tasks.xaml.cs, I created an instance of the view model class (TasksViewModel) in the constructor and set it as the DataContext for the control. The Tasks page will load one of two child UserControls depending on whether you are viewing the list of tasks (List.xaml) or the form for editing a task (Details.xaml). // Set the DataContext to an instance of the view model class var viewModel = new TasksViewModel(); DataContext = viewModel;   // Child user controls (inherit DataContext from this user control) List = new List(); // RadGridView Details = new Details(); // Form When the page first loads, the List is loaded into the ContentControl. // Show the RadGridView first ContentControl1.Content = List; In the code-behind we also listen for a couple of the view models events. The ItemSelected event will be fired when the user clicks on a record in the RadGridView in the List control. The SaveCompleted event will be fired when the user clicks Save in the Details control (the form). Here the view model is in control, and is letting the view know when something needs to change. // Listeners for the view model's events viewModel.ItemSelected += OnItemSelected; viewModel.SaveCompleted += OnSaveCompleted; The event handlers toggle the view between the RadGridView (List) and the form (Details). void OnItemSelected(object sender, RoutedEventArgs e) {     // Show the form     ContentControl1.Content = Details; }   void OnSaveCompleted(object sender, RoutedEventArgs e) {     // Show the RadGridView     ContentControl1.Content = List; } In TasksViewModel, we instantiate a DataContext object and a SaveCommand in the constructor. DataContext is a WCF RIA Services object that well use to retrieve the list of Tasks and to save any changes to a task. Ill talk more about this and Commands in future post, but for now think of the SaveCommand as an event handler that is called when the Save button in the form is clicked. DataContext = new DataContext(); SaveCommand = new DelegateCommand(OnSave); When the TasksViewModel constructor is called we also make a call to LoadTasks. This sets IsLoading to true (which causes the RadGridViews busy indicator to appear) and retrieves the records via WCF RIA Services.         public LoadOperation<Task> LoadTasks()         {             // Show the loading message             IsLoading = true;             // Get the data via WCF RIA Services. When the call has returned, called OnTasksLoaded.             return DataContext.Load(DataContext.GetTasksQuery(), OnTasksLoaded, false);         } When the data is returned, OnTasksLoaded is called. This sets IsLoading to false (which hides the RadGridViews busy indicator), and fires property changed notifications to the UI to let it know that the IsLoading and Tasks properties have changed. This property changed notification basically tells the UI to rebind. void OnTasksLoaded(LoadOperation<Task> lo) {     // Hide the loading message     IsLoading = false;       // Notify the UI that Tasks and IsLoading properties have changed     this.OnPropertyChanged(p => p.Tasks);     this.OnPropertyChanged(p => p.IsLoading); } Next lets look at the view models SelectedItem property. This is the one thats bound to both the RadGridView and the form. When the user clicks a record in the RadGridView its setter gets called (set a breakpoint and see what I mean). The other code in the setter lets the UI know that the SelectedItem has changed (so the form displays the correct data), and fires the event that notifies the UI that a selection has occurred (which tells the UI to switch from List to Details). public Task SelectedItem {     get { return _selectedItem; }     set     {         _selectedItem = value;           // Let the UI know that the SelectedItem has changed (forces it to re-bind)         this.OnPropertyChanged(p => p.SelectedItem);         // Notify the UI, so it can switch to the Details (form) page         NotifyItemSelected();     } } One last thing, saving the data. When the Save button in the form is clicked it fires the SaveCommand, which calls the OnSave method in the view model (once again, set a breakpoint to see it in action). public void OnSave() {     // Save the changes via WCF RIA Services. When the save is complete, call OnSaveCompleted.     DataContext.SubmitChanges(OnSaveCompleted, null); } In OnSave, we tell WCF RIA Services to submit any changes, which there will be if you changed either the Name or the Due Date in the form. When the save is completed, it calls OnSaveCompleted. This method fires a notification back to the UI that the save is completed, which causes the RadGridView (List) to show again. public virtual void OnSaveCompleted(SubmitOperation so) {     // Clear the item that is selected in the grid (in case we want to select it again)     SelectedItem = null;     // Notify the UI, so it can switch back to the List (RadGridView) page     NotifySaveCompleted(); } Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • ASP.NET MVC 3 Hosting :: New Features in ASP.NET MVC 3

    - by mbridge
    Razor View Engine The Razor view engine is a new view engine option for ASP.NET MVC that supports the Razor templating syntax. The Razor syntax is a streamlined approach to HTML templating designed with the goal of being a code driven minimalist templating approach that builds on existing C#, VB.NET and HTML knowledge. The result of this approach is that Razor views are very lean and do not contain unnecessary constructs that get in the way of you and your code. ASP.NET MVC 3 Preview 1 only supports C# Razor views which use the .cshtml file extension. VB.NET support will be enabled in later releases of ASP.NET MVC 3. For more information and examples, see Introducing “Razor” – a new view engine for ASP.NET on Scott Guthrie’s blog. Dynamic View and ViewModel Properties A new dynamic View property is available in views, which provides access to the ViewData object using a simpler syntax. For example, imagine two items are added to the ViewData dictionary in the Index controller action using code like the following: public ActionResult Index() {          ViewData["Title"] = "The Title";          ViewData["Message"] = "Hello World!"; } Those properties can be accessed in the Index view using code like this: <h2>View.Title</h2> <p>View.Message</p> There is also a new dynamic ViewModel property in the Controller class that lets you add items to the ViewData dictionary using a simpler syntax. Using the previous controller example, the two values added to the ViewData dictionary can be rewritten using the following code: public ActionResult Index() {     ViewModel.Title = "The Title";     ViewModel.Message = "Hello World!"; } “Add View” Dialog Box Supports Multiple View Engines The Add View dialog box in Visual Studio includes extensibility hooks that allow it to support multiple view engines, as shown in the following figure: Service Location and Dependency Injection Support ASP.NET MVC 3 introduces improved support for applying Dependency Injection (DI) via Inversion of Control (IoC) containers. ASP.NET MVC 3 Preview 1 provides the following hooks for locating services and injecting dependencies: - Creating controller factories. - Creating controllers and setting dependencies. - Setting dependencies on view pages for both the Web Form view engine and the Razor view engine (for types that derive from ViewPage, ViewUserControl, ViewMasterPage, WebViewPage). - Setting dependencies on action filters. Using a Dependency Injection container is not required in order for ASP.NET MVC 3 to function properly. Global Filters ASP.NET MVC 3 allows you to register filters that apply globally to all controller action methods. Adding a filter to the global filters collection ensures that the filter runs for all controller requests. To register an action filter globally, you can make the following call in the Application_Start method in the Global.asax file: GlobalFilters.Filters.Add(new MyActionFilter()); The source of global action filters is abstracted by the new IFilterProvider interface, which can be registered manually or by using Dependency Injection. This allows you to provide your own source of action filters and choose at run time whether to apply a filter to an action in a particular request. New JsonValueProviderFactory Class The new JsonValueProviderFactory class allows action methods to receive JSON-encoded data and model-bind it to an action-method parameter. This is useful in scenarios such as client templating. Client templates enable you to format and display a single data item or set of data items by using a fragment of HTML. ASP.NET MVC 3 lets you connect client templates easily with an action method that both returns and receives JSON data. Support for .NET Framework 4 Validation Attributes and IvalidatableObject The ValidationAttribute class was improved in the .NET Framework 4 to enable richer support for validation. When you write a custom validation attribute, you can use a new IsValid overload that provides a ValidationContext instance. This instance provides information about the current validation context, such as what object is being validated. This change enables scenarios such as validating the current value based on another property of the model. The following example shows a sample custom attribute that ensures that the value of PropertyOne is always larger than the value of PropertyTwo: public class CompareValidationAttribute : ValidationAttribute {     protected override ValidationResult IsValid(object value,              ValidationContext validationContext) {         var model = validationContext.ObjectInstance as SomeModel;         if (model.PropertyOne > model.PropertyTwo) {            return ValidationResult.Success;         }         return new ValidationResult("PropertyOne must be larger than PropertyTwo");     } } Validation in ASP.NET MVC also supports the .NET Framework 4 IValidatableObject interface. This interface allows your model to perform model-level validation, as in the following example: public class SomeModel : IValidatableObject {     public int PropertyOne { get; set; }     public int PropertyTwo { get; set; }     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {         if (PropertyOne <= PropertyTwo) {            yield return new ValidationResult(                "PropertyOne must be larger than PropertyTwo");         }     } } New IClientValidatable Interface The new IClientValidatable interface allows the validation framework to discover at run time whether a validator has support for client validation. This interface is designed to be independent of the underlying implementation; therefore, where you implement the interface depends on the validation framework in use. For example, for the default data annotations-based validator, the interface would be applied on the validation attribute. Support for .NET Framework 4 Metadata Attributes ASP.NET MVC 3 now supports .NET Framework 4 metadata attributes such as DisplayAttribute. New IMetadataAware Interface The new IMetadataAware interface allows you to write attributes that simplify how you can contribute to the ModelMetadata creation process. Before this interface was available, you needed to write a custom metadata provider in order to have an attribute provide extra metadata. This interface is consumed by the AssociatedMetadataProvider class, so support for the IMetadataAware interface is automatically inherited by all classes that derive from that class (notably, the DataAnnotationsModelMetadataProvider class). New Action Result Types In ASP.NET MVC 3, the Controller class includes two new action result types and corresponding helper methods. HttpNotFoundResult Action The new HttpNotFoundResult action result is used to indicate that a resource requested by the current URL was not found. The status code is 404. This class derives from HttpStatusCodeResult. The Controller class includes an HttpNotFound method that returns an instance of this action result type, as shown in the following example: public ActionResult List(int id) {     if (id < 0) {                 return HttpNotFound();     }     return View(); } HttpStatusCodeResult Action The new HttpStatusCodeResult action result is used to set the response status code and description. Permanent Redirect The HttpRedirectResult class has a new Boolean Permanent property that is used to indicate whether a permanent redirect should occur. A permanent redirect uses the HTTP 301 status code. Corresponding to this change, the Controller class now has several methods for performing permanent redirects: - RedirectPermanent - RedirectToRoutePermanent - RedirectToActionPermanent These methods return an instance of HttpRedirectResult with the Permanent property set to true. Breaking Changes The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller with the same Order as those on an action method were executed before the exception filters on the action method. This would typically be the case when exception filters were applied without a specified order Order value. In MVC 3, this order has been reversed in order to allow the most specific exception handler to execute first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order. Known Issues When you are editing a Razor view (CSHTML file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.

    Read the article

  • Using Unit of Work design pattern / NHibernate Sessions in an MVVM WPF

    - by Echiban
    I think I am stuck in the paralysis of analysis. Please help! I currently have a project that Uses NHibernate on SQLite Implements Repository and Unit of Work pattern: http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/10/nhibernate-and-the-unit-of-work-pattern.aspx MVVM strategy in a WPF app Unit of Work implementation in my case supports one NHibernate session at a time. I thought at the time that this makes sense; it hides inner workings of NHibernate session from ViewModel. Now, according to Oren Eini (Ayende): http://msdn.microsoft.com/en-us/magazine/ee819139.aspx He convinces the audience that NHibernate sessions should be created / disposed when the view associated with the presenter / viewmodel is disposed. He presents issues why you don't want one session per windows app, nor do you want a session to be created / disposed per transaction. This unfortunately poses a problem because my UI can easily have 10+ view/viewmodels present in an app. He is presenting using a MVP strategy, but does his advice translate to MVVM? Does this mean that I should scrap the unit of work and have viewmodel create NHibernate sessions directly? Should a WPF app only have one working session at a time? If that is true, when should I create / dispose a NHibernate session? And I still haven't considered how NHibernate Stateless sessions fit into all this! My brain is going to explode. Please help!

    Read the article

  • Dynamically specify and change a Silverlight DataGrid's columns during runtime (MVVM)

    - by Biggert
    What's the best method of dynamically specifying DataGrid columns in the Silverlight DataGrid control at runtime following the MVVM pattern? What I'd like to do would be bind the "DataGrid.Columns" property to a property in my ViewModel so that, if the user adds/removes columns, I simply update the ViewModel property and the DataGrid would change. Problem is, the "DataGrid.Columns" property can't be bound to (I don't think). Because this property isn't available nor is the DataGrid control itself available at the ViewModel level, my current approach is to step outside of the MVVM pattern for this particular implementation and capture certain events in View's code-behind using MVVM Light's Messenger class and then talk directly with the DataGrid control to achieve this capability. I know this is a general statement to this approach without details but is there an easier way... or maybe not so much easier, but a better way that adheres to the MVVM pattern a little better? It's driving me crazy that the DataGrid control's Columns property can't be bound... seems like such a simple thing. FYI - Before it's suggested to use AutoGenerateColumns = True, the class being bound for each item in the collection that's bound to DataGrid.ItemsSource does not have individual properties to identify what is bound to the columns... it's a collection property that contains the columns in order to keep them completely dynamic so that particular path is out. Also, handling the AutoGeneratingColumns and using e.Cancel to show/hide columns is also iffy for this same reason (I think).

    Read the article

  • MVVM - ListBox SelectedItem Binding Property Going Null

    - by Peanut
    So i have a listbox: <ListBox x:Name="listbox" HorizontalAlignment="Left" Margin="8,8,0,8" Width="272" BorderBrush="{x:Null}" Background="{x:Null}" Foreground="{x:Null}" ItemsSource="{Binding MenuItems}" ItemTemplate="{DynamicResource MenuItemsTemplate}" SelectionChanged="ListBox_SelectionChanged" SelectedItem="{Binding SelectedItem}"> </ListBox> and i have this included in my viewmodel: public ObservableCollection<MenuItem> MenuItems { get { return menuitems; } set { menuitems = value; NotifyPropertyChanged("MenuItems"); } } public MenuItem SelectedItem { get { return selecteditem; } set { selecteditem = value; NotifyPropertyChanged("SelectedItem"); } } and also in my viewmodel: public void UpdateStyle() { ActiveHighlight = SelectedItem.HighlightColor; ActiveShadow = SelectedItem.ShadowColor; } So, the objective is to call UpdateStyle() whenever selectedchanged event is fired. So in the .CS file, i call UpdateStyle(). The problem is, whenever I get into the selectionchanged event method, my ViewModel.SelectedItem is always null. I tried debugging this to see if the binding was working correctly, and it is. When I click on an item in the listbox, the SelectedItem Set is triggered, setting the value... but somewhere inbetween that and the selected changed (In the CS File) It gets reset to Null. Can anyone help out? Thanks

    Read the article

  • Binding update adds news series to WPF Toolkit chart (instead of replacing/updating series)

    - by Mal Ross
    I'm currently recoding a bar chart in my app to make use of the Chart class in the WPF Toolkit. Using MVVM, I'm binding the ItemsSource of a ColumnSeries in my chart to a property on my viewmodel. Here's the relevant XAML: <charting:Chart> <charting:ColumnSeries ItemsSource="{Binding ScoreDistribution.ClassScores}" IndependentValuePath="ClassName" DependentValuePath="Score"/> </charting:Chart> And the property on the viewmodel: // NB: viewmodel derived from Josh Smith's BindableObject public class ExamResultsViewModel : BindableObject { // ... private ScoreDistributionByClass _scoreDistribution; public ScoreDistributionByClass ScoreDistribution { get { return _scoreDistribution; } set { if (_scoreDistribution == value) { return; } _scoreDistribution = value; RaisePropertyChanged(() => ScoreDistribution); } } However, when I update the ScoreDistribution property (by setting it to a new ScoreDistribution object), the chart gets an additional series (based on the new ScoreDistribution) as well as keeping the original series (based on the previous ScoreDistribution). To illustrate this, here are a couple of screenshots showing the chart before an update (with a single data point in ScoreDistribution.ClassScores) and after it (now with 3 data points in ScoreDistribution.ClassScores): Now, I realise there are other ways I could be doing this (e.g. changing the contents of the original ScoreDistribution object rather than replacing it entirely), but I don't understand why it's going wrong in its current form. Can anyone help?

    Read the article

  • I got MVVM 3-Level-Master-Detail Switchting working but with CRUD operations now everything seems st

    - by msfanboy
    Hello, I have 1 UserControl (SchoolclassAdministration.xaml) that is datatemplated with 1 ViewModel (SchoolclassAdministrationViewModel) I have 3 Models and 3 ViewModels in that scenario. Those 3 ViewModels must reflect the requirements of the View. The requirements are 3 "Areas" on the left side and 2 "Areas" on the right side. 3: SchoolclassFormular PupilFormular SubjectFormular Those have all Buttons for Add/Delete 2: PupilsDataGrid SubjectsDataGrid The Master-Detail scenario is between the: SchoolclassFormular = PupilsDataGrid = SubjectsDataGrid The switching of the ViewModelCollections work! My Problem scenario is this: The DataContext is on the SchoolclassAdministrationViewModel what is the ViewModel containing the AllSchoolclassesViewModel ObservableCollection bound to the SchoolclassAdministration.xaml UserControl. My SchoolclassViewModel,PupilViewModel and SubjectViewModel has all Properties, Commands(Add/Delete). My Question: How can I set these 3 ViewModels as DataContext to my ONE SchoolclassAdministration.xaml UserControl I have? Before you answer... putting every ViewModel(schoolclass,pupil,subject) in its own UserControl will not help me because then the Master-Detail switching can NOT work anymore. Every related ViewModels need to be put in a related/ONE UserControl. OK now I can`t wait for an answer because that scenario is driving me nuts for weeks.

    Read the article

  • mvvm - prismv2 - INotifyPropertyChanged

    - by depictureboy
    Since this is so long and prolapsed and really doesnt ask a coherent question: 1: what is the proper way to implement subproperties of a primary object in a viewmodel? 2: Has anyone found a way to fix the delegatecommand.RaiseCanExecuteChanged issue? or do I need to fix it myself until MS does? For the rest of the story...continue on. In my viewmodel i have a doctor object property that is tied to my Model.Doctor, which is an EF POCO object. I have onPropertyChanged("Doctor") in the setter as such: Private Property Doctor() As Model.Doctor Get Return _objDoctor End Get Set(ByVal Value As Model.Doctor) _objDoctor = Value OnPropertyChanged("Doctor") End Set End Property The only time OnPropertyChanged fires if the WHOLE object changes. This wouldnt be a problem except that I need to know when the properties of doctor changes, so that I can enable other controls on my form(save button for example). I have tried to implement it in this way: Public Property FirstName() As String Get Return _objDoctor.FirstName End Get Set(ByVal Value As String) _objDoctor.FirstName = Value OnPropertyChanged("Doctor") End Set End Property this is taken from the XAMLPowerToys controls from Karl Shifflet, so i have to assume that its correct. But for the life of me I cant get it to work. I have included PRISM in here because I am using a unity container to instantiate my view and it IS a singleton. I am getting change notification to the viewmodel via eventaggregator that then populates Doctor with the new value. The reason I am doing all this is because of PRISM's DelegateCommand. So maybe that is my real issue. It appears that there is a bug in DelegateCommand that does not fire the RaiseCanExecuteChanged method on the commands that implement it and therefore needs to be fired manually. I have the code for that in my onPropertyChangedEventHandler. Of course this isnt implemented through the ICommand interface either so I have to break and make my properties DelegateCommand(of X) so that I have access to RaiseCanExecuteChanged of each command.

    Read the article

  • How have you successfully implemented MessageBox.Show() functionality in MVVM?

    - by Edward Tanguay
    I've got a WPF application which calls MessageBox.Show() way back in the ViewModel (to check if the user really wants to delete). This actually works, but goes against the grain of MVVM since the ViewModel should not explicitly determine what happens on the View. So now I am thinking how can I best implement the MessageBox.Show() functionality in my MVVM application, options: I could have a message with the text "Are you sure...?" along with two buttons Yes and No all in a Border in my XAML, and create a trigger on the template so that it is collapsed/visible based on a ViewModelProperty called AreYourSureDialogueBoxIsVisible, and then when I need this dialogue box, assign AreYourSureDialogueBoxIsVisible to "true", and also handle the two buttons via DelegateCommand back in my ViewModel. I could also somehow try to handle this with triggers in XAML so that the Delete button actually just makes some Border element appear with the message and buttons in it, and the Yes button did the actually deleting. Both solutions seem to be too complex for what used to be a couple lines of code with MessageBox.Show(). In what ways have you successfully implemented Dialogue Boxes in your MVVM applications?

    Read the article

  • Asp.net MVC 2, MvcContrib, and a base controller with redirect actions

    - by jeriley
    I've got a base controller that takes a couple generics, nothing overly fancy. public class SystemBaseController<TForm, TFormViewModel> : Controller where TForm : class, IForm where TFormViewModel : class, IViewModel ok, no big deal. I have a method "CompleteForm" that takes in the viewModel, looks kinda like this ... public ActionResult CompleteForm(TFormViewModel viewModel) { //does some stuff return this.RedirectToAction(c => c.FormInfo(viewModel)); } Problem is, the controller that inherits this, like so public class SalesFormController : SystemBaseController<SalesForm, SalesViewModel> { } I end up getting a error from MvcContrib - Controller name must end in 'Controller' at this point ... public RedirectToRouteResult(Expression<Action<T>> expression) : this(expression, expr => Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(expr)) {} The expression that's passed in is correct (SystemBaseController blahblah) but I'm not sure why its 1.) saying there's no controller at the end, and 2.) if I pull out everything into the controller (out of the base), works just fine. Do I need to write or setup some kind of action filter of my own or what am I missing?

    Read the article

  • MVVM: Thin ViewModels and Rich Models

    - by Dan Bryant
    I'm continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges. One of these challenges is figuring out how to get the benefits of decoupling with this pattern without creating a lot of repetitive, hard-to-maintain code. My current strategy has been to create 'rich' Model classes. They are fully aware that they will be consumed by an MVVM pattern and implement INotifyPropertyChanged, allow their collections to be observed and remain cognizant that they may always be under observation. My ViewModel classes tend to be thin, only exposing properties when data actually needs to be transformed, with the bulk of their code being RelayCommand handlers. Views happily bind to either ViewModels or Models directly, depending on whether any data transformation is required. I use AOP (via Postsharp) to ease the pain of INotifyPropertyChanged, making it easy to make all of my Model classes 'rich' in this way. Are there significant disadvantages to using this approach? Can I assume that the ViewModel and View are so tightly coupled that if I need new data transformation for the View, I can simply add it to the ViewModel as needed?

    Read the article

  • Using Moq callbacks correctly according to AAA

    - by Hadi Eskandari
    I've created a unit test that tests interactions on my ViewModel class in a Silverlight application. To be able to do this test, I'm mocking the service interface, injected to the ViewModel. I'm using Moq framework to do the mocking. to be able to verify bounded object in the ViewModel is converted properly, I've used a callback: [Test] public void SaveProposal_Will_Map_Proposal_To_WebService_Parameter() { var vm = CreateNewCampaignViewModel(); var proposal = CreateNewProposal(1, "New Proposal"); Services.Setup(x => x.SaveProposalAsync(It.IsAny<saveProposalParam>())).Callback((saveProposalParam p) => { Assert.That(p.plainProposal, Is.Not.Null); Assert.That(p.plainProposal.POrderItem.orderItemId, Is.EqualTo(1)); Assert.That(p.plainProposal.POrderItem.orderName, Is.EqualTo("New Proposal")); }); proposal.State = ObjectStates.Added; vm.CurrentProposal = proposal; vm.Save(); } It is working fine, but if you've noticed, using this mechanism the Assert and Act part of the unit test have switched their parts (Assert comes before Acting). Is there a better way to do this, while preserving correct AAA order?

    Read the article

  • Silverlight MVVM binding seems not to work

    - by Savvas Sopiadis
    Hi everybody! Building my first SL MVVM application (Silverlight4 RC) and have some issues i don't understand. Having a WPF background i don't know what is going on here: ViewModel has several properties, in which one is called SelectedRecord. This is a get only property and is defined like this: public Culture SelectedRecord { get { return culturesView.View.CurrentItem as Culture; } } As you can see it is gets the current value of a CollectionViewSource (called culturesView). So if i select a Culture, the SelectedRecord (gets a value directly from within the CollectionViewSource) as expected. (Actually there is a datagrid control bound to the CollectionViewSource, hence it is possible to change the selected item) OK. Now to the View . There are several views which access this ViewModel and in particular there is one which shows the values of the aforementioned property SelectedRecord (let's call it the EditView). To show this EditView there is a button (which has its Command property bound to an ICommand in the ViewModel) which functions (the first time) as expected. This means: 1st try : i select a record, switch to EditView, outcome: selected record values are shown (as expected!!). 2nd try: switch back to datagrid, select another record, switch to EditView, outcome: the values of the previous shown record are shown again!!! WHY?? First i thought that the SelectedRecord has not the correct value set, but i was mistaken: it HAS the correct value! So it should be shown!? What am i missing? In WPF this would work!! Thanks in advance

    Read the article

  • MVVM-Light EventToCommand Behavior for CheckBox Checked/Unchecked in Silverlight

    - by George Durzi
    I would like to handle the Checked and Unchecked events of a Checkbox control and execute a command in my ViewModel. I wired up an EventTrigger for both the Checked and Unchecked events as follows: <CheckBox x:Name="chkIsExtendedHr" IsChecked="{Binding Schedule.Is24Hour, Mode=TwoWay}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Checked"> <GalaSoft_MvvmLight_Command:EventToCommand CommandParameter="{Binding IsChecked, ElementName=chkIsExtendedHr}" Command="{Binding Path=SetCloseTime, Mode=OneWay}" /> </i:EventTrigger> <i:EventTrigger EventName="Unchecked"> <GalaSoft_MvvmLight_Command:EventToCommand CommandParameter="{Binding IsChecked, ElementName=chkIsExtendedHr}" Command="{Binding Path=SetCloseTime, Mode=OneWay}" /> </i:EventTrigger> </i:Interaction.Triggers> </CheckBox> I defined a RelayCommand in my ViewModel and wired up an action for it: public RelayCommand<Boolean> SetCloseTime{ get; private set; } ... SetCloseTime= new RelayCommand<bool>(ExecuteSetCloseTime); The parameter in the action for the command always resolves to the previous state of the CheckBox, e.g. false when the CheckBox is checked, and true when the CheckBox is unchecked. void ExecuteSetCloseTime(bool isChecked) { if (isChecked) { // do something } } Is this expected behavior? I have a workaround where I have separate triggers (and commands) for the Checked and Unchecked and use a RelayCommand instead of RelayCommand<bool>. Each command executes correctly when the CheckBox is checked and unchecked. Feels a little dirty though - even dirtier than having UI code in my ViewModel :) Thanks

    Read the article

  • Verify an event was raised by mocked object

    - by joblot
    In my unit test how can I verify that an event is raised by the mocked object. I have a View(UI) -- ViewModel -- DataProvider -- ServiceProxy. ServiceProxy makes async call to serivce operation. When async operation is complete a method on DataProvider is called (callback method is passed as a method parameter). The callback method then raise and event which ViewModel is listening to. For ViewModel test I mock DataProvider and verify that handler exists for event raised by DataProvider. When testing DataProvider I mock ServiceProxy, but how can I test that callback method is called and event is raised. I am using RhinoMock 3.5 and AAA syntax Thanks -- DataProvider -- public partial class DataProvider { public event EventHandler<EntityEventArgs<ProductDefinition>> GetProductDefinitionCompleted; public void GetProductDefinition() { var service = IoC.Resolve<IServiceProxy>(); service.GetProductDefinitionAsync(GetProductDefinitionAsyncCallback); } private void GetProductDefinitionAsyncCallback(ProductDefinition productDefinition, ServiceError error) { OnGetProductDefinitionCompleted(this, new EntityEventArgs<ProductDefinition>(productDefinition, error)); } protected void OnGetProductDefinitionCompleted(object sender, EntityEventArgs<ProductDefinition> e) { if (GetProductDefinitionCompleted != null) GetProductDefinitionCompleted(sender, e); } } -- ServiceProxy -- public class ServiceProxy : ClientBase<IService>, IServiceProxy { public void GetProductDefinitionAsync(Action<ProductDefinition, ServiceError> callback) { Channel.BeginGetProductDefinition(EndGetProductDefinition, callback); } private void EndGetProductDefinition(IAsyncResult result) { Action<ProductDefinition, ServiceError> callback = result.AsyncState as Action<ProductDefinition, ServiceError>; ServiceError error; ProductDefinition results = Channel.EndGetProductDefinition(out error, result); if (callback != null) callback(results, error); } }

    Read the article

  • MVC: Submit one form from a page with multiple forms

    - by Rob
    I'm working in an ASP.NET 3.5 MVC application where i've got a view with multiple forms in it. Form 1 contains information about products and will form a shoppingcart with a remove button. Form 2 is as below and is to be used to get the information from the shoppingcart and create an order of it. <% using (Html.BeginForm()) { %> <%=Html.Hidden(Order.ProductId", "E63EF586-F625-4C8D-B82E-E63A6FA4A63C")%> <%=Html.Hidden(Order.Amount", 1)%> <input type="submit" value="Pay" /> <%} % The first form contains a similar beginform with a foreach loop to get the information about the products from the model. When i use the submit button on the second form everything seems to be submitted and the action in the controller for the first form is trying to handle the request. That is where the error occurce because the information in the viewmodel isn't corresponding to what is being expected. The controller which is trying to handle the request: [AcceptVerbs(HttpVerbs.Post)] public ActionResult ShowShoppingcartForm([Bind(Prefix = "Order")] MyViewmodel viewModel) { //.. } The controller which is expected to handle the request: [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveOrder([Bind(Prefix = "Order")] MyViewmodel viewModel) { throw new NotImplementedException(); }

    Read the article

  • Binding update on adds news series to WPF Toolkit chart (instead of replacing/updating series)

    - by Mal Ross
    I'm currently recoding a bar chart in my app to make use of the Chart class in the WPF Toolkit. Using MVVM, I'm binding the ItemsSource of a ColumnSeries in my chart to a property on my viewmodel. Here's the relevant XAML: <charting:Chart> <charting:ColumnSeries ItemsSource="{Binding ScoreDistribution.ClassScores}" IndependentValuePath="ClassName" DependentValuePath="Score"/> </charting:Chart> And the property on the viewmodel: // NB: viewmodel derived from Josh Smith's BindableObject public class ExamResultsViewModel : BindableObject { // ... private ScoreDistributionByClass _scoreDistribution; public ScoreDistributionByClass ScoreDistribution { get { return _scoreDistribution; } set { if (_scoreDistribution == value) { return; } _scoreDistribution = value; RaisePropertyChanged(() => ScoreDistribution); } } However, when I update the ScoreDistribution property (by setting it to a new ScoreDistribution object), the chart gets an additional series (based on the new ScoreDistribution) as well as keeping the original series (based on the previous ScoreDistribution). To illustrate this, here are a couple of screenshots showing the chart before an update (with a single data point in ScoreDistribution.ClassScores) and after it (now with 3 data points in ScoreDistribution.ClassScores): Now, I realise there are other ways I could be doing this (e.g. changing the contents of the original ScoreDistribution object rather than replacing it entirely), but I don't understand why it's going wrong in its current form. Can anyone help?

    Read the article

  • How do you send in the LayoutRoot into a RelayCommand via a EventToCommand?

    - by user298145
    Grid example with the trigger: <Grid x:Name="LayoutRoot" DataContext="{Binding ProjectGrid, Source={StaticResource Locator}}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding LoadedCommand, Mode=OneWay}" PassEventArgsToCommand="True"/> </i:EventTrigger> </i:Interaction.Triggers> In my ViewModel I set the LoadedCommand like this: public RelayCommand<RoutedEventArgs> LoadedCommand {get;private set;} And in the ViewModel initializer I have this: public ProjectGridViewModel() { LoadedCommand = new RelayCommand<RoutedEventArgs>(e => { this.DoLoaded(e); } ); } Then, in my DoLoaded I'm trying to do this: Grid _projectGrid = null; public void DoLoaded(RoutedEventArgs e) { _projectGrid = e.OriginalSource as Grid; } You can see I'm trying to get rid of my Loaded="" in my Grid in my view, and do a RelayCommand instead. The issue is the OriginalSource brings back nothing. My loaded event is running nice this way, but I need to get the Grid in via the RoutedEventArgs it seems. I tried passing in the Grid in the EventCommand with CommandParameter="{Binding ElementName=LayoutRoot}", but this just crashes VS2010 when hitting F5 and running the project. Any ideas? Or a better way to do this? I had the Loaded event run in the views C# then call the ViewModel in the Views code-behind, but I'd like to do a nicer binding. Talking to the ViewMode in the Views code-behind feels like a hack.

    Read the article

  • MVVM and avoiding Monolithic God object

    - by bufferz
    I am in the completion stage of a large project that has several large components: image acquisition, image processing, data storage, factory I/O (automation project) and several others. Each of these components is reasonably independent, but for the project to run as a whole I need at least one instance of each component. Each component also has a ViewModel and View (WPF) for monitoring status and changing things. My question is the safest, most efficient, and most maintainable method of instantiating all of these objects, subscribing one class to an Event in another, and having a common ViewModel and View for all of this. Would it best if I have a class called God that has a private instance of all of these objects? I've done this in the past and regretted it. Or would it be better if God relied on Singleton instances of these objects to get the ball rolling. Alternatively, should Program.cs (or wherever Main(...) is) instantiate all of these components, and pass them to God as parameters and then let Him (snicker) and His ViewModel deal with the particulars of running this projects. Any other suggestions I would love to hear. Thank you!

    Read the article

  • How not to lose binding source updates?

    - by Fyodor Soikin
    Suppose I have a modal dialog with a textbox and OK/Cancel buttons. And it is built on MVVM - i.e. it has a ViewModel object with a string property that the textbox is bound to. Say, I enter some text in the textbox and then grab my mouse and click "OK". Everything works fine: at the moment of click, the textbox loses focus, which causes the binding engine to update the ViewModel's property. I get my data, everybody's happy. Now suppose I don't use my mouse. Instead, I just hit Enter on the keyboard. This also causes the "OK" button to "click", since it is marked as IsDefault="True". But guess what? The textbox doesn not lose focus in this case, and therefore, the binding engine remains innocently ignorant, and I don't get my data. Dang! Another variation of the same scenario: suppose I have a data entry form right in the main window, enter some data into it, and then hit Ctrl+S for "Save". Guess what? My latest entry doesn't get saved! This may be somewhat remedied by using UpdateSourceTrigger=PropertyChanged, but that is not always possible. One obvious case would be the use of StringFormat with binding - the text keeps jumping back into "formatted" state as I'm trying to enter it. And another case, which I have encountered myself, is when I have some time-consuming processing in the viewmodel's property setter, and I only want to perform it when the user is "done" entering text. This seems like an eternal problem: I remember trying to solve it systematically from ages ago, ever since I've started working with interactive interfaces, but I've never quite succeeded. In the past, I always ended up using some sort of hacks - like, say, adding an "EnsureDataSaved" method to every "presenter" (as in "MVP") and calling it at "critical" points, or something like that... But with all the cool technologies, as well as empty hype, of WPF, I expected they'd come up with some good solution.

    Read the article

  • How to "DRY up" C# attributes in Models and ViewModels?

    - by DanM
    This question was inspired by my struggles with ASP.NET MVC, but I think it applies to other situations as well. Let's say I have an ORM-generated Model and two ViewModels (one for a "details" view and one for an "edit" view): Model public class FooModel // ORM generated { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public int Age { get; set; } public int CategoryId { get; set; } } Display ViewModel public class FooDisplayViewModel // use for "details" view { [DisplayName("ID Number")] public int Id { get; set; } [DisplayName("First Name")] public string FirstName { get; set; } [DisplayName("Last Name")] public string LastName { get; set; } [DisplayName("Email Address")] [DataType("EmailAddress")] public string EmailAddress { get; set; } public int Age { get; set; } [DisplayName("Category")] public string CategoryName { get; set; } } Edit ViewModel public class FooEditViewModel // use for "edit" view { [DisplayName("First Name")] // not DRY public string FirstName { get; set; } [DisplayName("Last Name")] // not DRY public string LastName { get; set; } [DisplayName("Email Address")] // not DRY [DataType("EmailAddress")] // not DRY public string EmailAddress { get; set; } public int Age { get; set; } [DisplayName("Category")] // not DRY public SelectList Categories { get; set; } } Note that the attributes on the ViewModels are not DRY--a lot of information is repeated. Now imagine this scenario multiplied by 10 or 100, and you can see that it can quickly become quite tedious and error prone to ensure consistency across ViewModels (and therefore across Views). How can I "DRY up" this code? Before you answer, "Just put all the attributes on FooModel," I've tried that, but it didn't work because I need to keep my ViewModels "flat". In other words, I can't just compose each ViewModel with a Model--I need my ViewModel to have only the properties (and attributes) that should be consumed by the View, and the View can't burrow into sub-properties to get at the values. Update LukLed's answer suggests using inheritance. This definitely reduces the amount of non-DRY code, but it doesn't eliminate it. Note that, in my example above, the DisplayName attribute for the Category property would need to be written twice because the data type of the property is different between the display and edit ViewModels. This isn't going to be a big deal on a small scale, but as the size and complexity of a project scales up (imagine a lot more properties, more attributes per property, more views per model), there is still the potentially for "repeating yourself" a fair amount. Perhaps I'm taking DRY too far here, but I'd still rather have all my "friendly names", data types, validation rules, etc. typed out only once.

    Read the article

  • Dynamic Scoped Resources in WPF/XAML?

    - by firoso
    I have 2 Xaml files, one containing a DataTemplate which has a resource definition for an Image brush, and the other containing a content control which presents this DataTemplate. The data template is bound to a view model class. Everything seems to work EXCEPT the ImageBrush resource, which just shows up white... Any ideas? File 1: DataTemplate for ViewModel <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:SEL.MfgTestDev.ESS.ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <DataTemplate DataType="{x:Type vm:PresenterViewModel}"> <DataTemplate.Resources> <ImageBrush x:Key="PresenterTitleBarFillBrush" TileMode="Tile" Viewbox="{Binding Path=FillBrushDimensions, Mode=Default}" ViewboxUnits="Absolute" Viewport="{Binding Path=FillBrushPatternSize, Mode=Default}" ViewportUnits="Absolute" ImageSource="{Binding Path=FillImage, Mode=Default}"/> </DataTemplate.Resources> <Grid d:DesignWidth="1440" d:DesignHeight="900"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="192"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="120"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <DockPanel HorizontalAlignment="Stretch" Width="Auto" LastChildFill="True" Background="{x:Null}" Grid.ColumnSpan="2"> <Image Source="{Binding Path=ImageSource, Mode=Default}"/> <Rectangle Fill="{DynamicResource PresenterTitleBarFillBrush}"/> </DockPanel> </Grid> </DataTemplate> </ResourceDictionary> File 2: Main Window Class which instanciates the DataTemplate Via it's view model. <Window x:Class="SEL.MfgTestDev.ESS.ESSMainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:SEL.MfgTestDev.ESS.ViewModel" Title="ESS Control Window" Height="900" Width="1440" WindowState="Maximized" WindowStyle="None" ResizeMode="NoResize" DataContext="{Binding}"> <Window.Resources> <ResourceDictionary Source="PresenterViewModel.xaml" /> </Window.Resources> <ContentControl> <ContentControl.Content> <vm:PresenterViewModel ImageSource="XAMLResources\SEL25YearsTitleBar.bmp" FillImage="XAMLResources\SEL25YearsFillPattern.bmp" FillBrushDimensions="0,0,5,110" FillBrushPatternSize="0,0,5,120"/> </ContentControl.Content> </ContentControl> </Window> And for the sake of completeness! The CodeBehind for the View Model using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SEL.MfgTestDev.ESS.ViewModel { public class PresenterViewModel : ViewModelBase { public PresenterViewModel() { } //DataBindings private ImageSource _imageSource; public ImageSource ImageSource { get { return _imageSource; } set { if (_imageSource != value) { _imageSource = value; OnPropertyChanged("ImageSource"); } } } private Rect _fillBrushPatternSize; public Rect FillBrushPatternSize { get { return _fillBrushPatternSize; } set { if (_fillBrushPatternSize != value) { _fillBrushPatternSize = value; OnPropertyChanged("FillBrushPatternSize"); } } } private Rect _fillBrushDimensions; public Rect FillBrushDimensions { get { return _fillBrushDimensions; } set { if (_fillBrushDimensions != value) { _fillBrushDimensions = value; OnPropertyChanged("FillBrushDimensions"); } } } private ImageSource _fillImage; public ImageSource FillImage { get { return _fillImage; } set { if (_fillImage != value) { _fillImage = value; OnPropertyChanged("FillImage"); } } } } }

    Read the article

  • How to bind dropdownlist data to complex class?

    - by chobo2
    Hi I am using asp.net mvc 2.0(default binding model) and I have this problem. I have a strongly typed view that has a dropdownlist <%= Html.DropDownList("List", "-----")%> Now I have a model class like Public class Test() { public List { get; set; } public string Selected {get; set;} } Now I have in my controller this public ActionResult TestAction() { Test ViewModel = new Test(); ViewModel.List = new SelectList(GetList(), "value", "text", "selected"); return View(Test); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult TestAction(Test ViewModel) { return View(); } Now when I load up the TestAction page for the first time it populates the dropdown list as expected. Now I want to post the selected value back to the server(the dropdownlist is within a form tag with some other textboxes). So I am trying to bind it automatically when it comes in as seen (Test ViewModel) However I get this big nasty error. Server Error in '/' Application. No parameterless constructor defined for this object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: No parameterless constructor defined for this object. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241 System.Activator.CreateInstance(Type type, Boolean nonPublic) +69 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403 System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479 System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +474 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 So how can I do this?

    Read the article

  • Partial view is not rendering within the main view it's contained (instead it's rendered in it's own page)?

    - by JaJ
    I have a partial view that is contained in a simple index view. When I try to add a new object to my model and update my partial view to display that new object along with existing objects the partial view is rendered outside the page that it's contained? I'm using AJAX to update the partial view but what is wrong with the following code? Model: public class Product { public int ID { get; set; } public string Name { get; set; } [DataType(DataType.Currency)] public decimal Price { get; set; } } public class BoringStoreContext { List<Product> results = new List<Product>(); public BoringStoreContext() { Products = new List<Product>(); Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) }); Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) }); } public List<Product> Products {get; set;} } public class ProductIndexViewModel { public Product NewProduct { get; set; } public IEnumerable<Product> Products { get; set; } } Index.cshtml View: @model AjaxPartialPageUpdates.Models.ProductIndexViewModel @using (Ajax.BeginForm("Index_AddItem", new AjaxOptions { UpdateTargetId = "productList" })) { <div> @Html.LabelFor(model => model.NewProduct.Name) @Html.EditorFor(model => model.NewProduct.Name) </div> <div> @Html.LabelFor(model => model.NewProduct.Price) @Html.EditorFor(model => model.NewProduct.Price) </div> <div> <input type="submit" value="Add Product" /> </div> } <div id='productList'> @{ Html.RenderPartial("ProductListControl", Model.Products); } </div> ProductListControl.cshtml Partial View @model IEnumerable<AjaxPartialPageUpdates.Models.Product> <table> <!-- Render the table headers. --> <tr> <th>Name</th> <th>Price</th> </tr> <!-- Render the name and price of each product. --> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(model => item.Name)</td> <td>@Html.DisplayFor(model => item.Price)</td> </tr> } </table> Controller: public class HomeController : Controller { public ActionResult Index() { BoringStoreContext db = new BoringStoreContext(); ProductIndexViewModel viewModel = new ProductIndexViewModel { NewProduct = new Product(), Products = db.Products }; return View(viewModel); } public ActionResult Index_AddItem(ProductIndexViewModel viewModel) { BoringStoreContext db = new BoringStoreContext(); db.Products.Add(viewModel.NewProduct); return PartialView("ProductListControl", db.Products); } }

    Read the article

  • Silverlight Cream for April 25, 2010 -- #847

    - by Dave Campbell
    In this Issue: Michael Washington, David Poll, Andrea Boschin, Kunal Chowdhury(-2-), Lee, and Chad Campbell. Shoutout: Not at all Silverlight, but Kirupa has a great article up about Elastic Collisions From SilverlightCream.com: Easily decouple your MVVM ViewModel from your Model using RX Extensions Michael Washington continues with his Simplified MVVM and uses Rx to allow him to put web service methods in the model and call them from the ViewModel. A “refreshing” Authentication/Authorization experience with Silverlight 4 David Poll expands on his previous post and demonstrates returning the user to the page prior to the login, just the way you'd like it. Using a PollingDuplex service to handle long running activities Andrea Boschin is back discussing PollingDuplex again, this time is discussing getting updates from a long-running process. Introduction to Silverlight - Silverlight tutorials Chapter 1 Kunal Chowdhury has an intro to Silverlight Tutorial that looks good... if you're just getting started, here's a place to look. Introduction to Silverlight Application Development - Silverlight tutorial Chapter 2 In his 2nd introductory tutorial, Kunal Chowdhury gets into code and discusses User Controls. Drag and Drop grouping in Datagrid Lee has a post up where he's taken a DataGrid and produced some of the features of some of the 3rd-party controls, specifically dragging column headers to a place above the grid to sort the grid. Silverlight – HTTP request to [Url] was aborted. …local channel being closed while the request was still in progress Chad Campbell is addressing timeout problems you may hit with connecting up to your WCF service. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >