Search Results

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

Page 1/36 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • MVVM load data during or after ViewModel construction?

    - by mkmurray
    My generic question is as the title states, is it best to load data during ViewModel construction or afterward through some Loaded event handling? I'm guessing the answer is after construction via some Loaded event handling, but I'm wondering how that is most cleanly coordinated between ViewModel and View? Here's more details about my situation and the particular problem I'm trying to solve: I am using the MVVM Light framework as well as Unity for DI. I have some nested Views, each bound to a corresponding ViewModel. The ViewModels are bound to each View's root control DataContext via the ViewModelLocator idea that Laurent Bugnion has put into MVVM Light. This allows for finding ViewModels via a static resource and for controlling the lifetime of ViewModels via a Dependency Injection framework, in this case Unity. It also allows for Expression Blend to see everything in regard to ViewModels and how to bind them. So anyway, I've got a parent View that has a ComboBox databound to an ObservableCollection in its ViewModel. The ComboBox's SelectedItem is also bound (two-way) to a property on the ViewModel. When the selection of the ComboBox changes, this is to trigger updates in other views and subviews. Currently I am accomplishing this via the Messaging system that is found in MVVM Light. This is all working great and as expected when you choose different items in the ComboBox. However, the ViewModel is getting its data during construction time via a series of initializing method calls. This seems to only be a problem if I want to control what the initial SelectedItem of the ComboBox is. Using MVVM Light's messaging system, I currently have it set up where the setter of the ViewModel's SelectedItem property is the one broadcasting the update and the other interested ViewModels register for the message in their constructors. It appears I am currently trying to set the SelectedItem via the ViewModel at construction time, which hasn't allowed sub-ViewModels to be constructed and register yet. What would be the cleanest way to coordinate the data load and initial setting of SelectedItem within the ViewModel? I really want to stick with putting as little in the View's code-behind as is reasonable. I think I just need a way for the ViewModel to know when stuff has Loaded and that it can then continue to load the data and finalize the setup phase. Thanks in advance for your responses.

    Read the article

  • return list from view to controller via viewmodel

    - by user232076
    I have a controller that takes in a viewmodel and submitbutton public ActionResult AddLocation(AddLocationViewModel viewModel, string submitButton) My view is bound to the viewmodel. The viewmodel contains a list objects used to create an html table with checkboxes. Is there a way to access the selected "rows" through the viewmodel in my controller? So that I can iterate through and get the selected items? Thanks LDD

    Read the article

  • Pass or Get a value from Parent ViewModel down to Sub-ViewModel?

    - by mkmurray
    I am using the MVVM Light framework as well as Unity for DI. I have some nested Views, each bound to a corresponding ViewModel. The ViewModels are bound to each View's root control DataContext via the ViewModelLocator idea that Laurent Bugnion has put into MVVM Light. This allows for finding ViewModels via a static resource and for controlling the lifetime of ViewModels via a Dependency Injection framework, in this case Unity. It also allows for Expression Blend to see everything in regard to ViewModels and how to bind them. As I stated the Views have a healthy dose of nesting, but the ViewModels don't really know anything about each other. A parent view binds to its corresponding ViewModel via the static resource ViewModelLocator (which uses Unity to control the construction and lifetime of the ViewModel object). That parent view contains a user control in it that is another sub-view, which then goes and gets its corresponding ViewModel via the ViewModelLocator as well. The ViewModels don't have references to each other or know any hierarchy in regard to each other. So here's an example of how the ViewModels do interact via messaging. I've got a parent View that has a ComboBox databound to an ObservableCollection in its ViewModel. The ComboBox's SelectedItem is also bound (two-way) to a property on the ViewModel. When the selection of the ComboBox changes, this is to trigger updates in other Views and sub-Views. Currently I am accomplishing this via the Messaging system that is found in MVVM Light. So I'm wondering what the best practice would be to get information from one ViewModel to another? In this case, what I need to pass down to sub-ViewModels is basically a user Guid representing the currently logged in user. The top-most parent View (well, ViewModel) will know this information, but I'm not sure how to get it down into the sub-ViewModels. Some possible approaches I can think of: Should the sub-ViewModel ask the static resource ViewModelLocator for a reference to the same object the parent View is using and access the property that way? It seems like ViewModels going through each other's properties is not very clean and couples them together unnecessarily. I'm already using messaging to notify the sub-Views that the user selected a new item in the ComboBox and to update accordingly. But the object type that is being selected in the ComboBox is not really directly related to this data value that the sub-Views need.

    Read the article

  • Is there a way to update a ViewModel in MVC2?

    - by Juvaly
    This code works: [HttpPost] public ActionResult Edit(int id, FormCollection fc) { Movie movie = ( from m in _ctx.Movie.Include("MovieActors") where m.MovieID == id select m ).First(); MovieActorViewModel movieActor = new MovieActorViewModel(movie); if (TryUpdateModel(movieActor)) { _ctx.ApplyPropertyChanges(movieActor.Movie.EntityKey.EntitySetName, movieActor.Movie); _ctx.SaveChanges(); } return View(movieActor); } However, I am not sure how to test this, and in general would much rather have the method take a typed model like: [HttpPost] public ActionResult Edit(MovieActorViewModel movieActor) Is this possible? What changes to my MovieActorViewModel class do I need to make in order to enable this? That class looks like this: public class MovieActorViewModel { public Movie Movie { get; set; } public Actor Actor { get; set; } public PublisherDealViewModel(Movie movie) { this.Movie = movie; this.Actor = ( from a in this.Movie.Actors where a.ActorID == 1 select a ).First(); } } The view is typed (inherits ViewPage) simple: <% using (Html.BeginForm()) {%> Movie Title: <%= Html.TextBoxFor(model=>model.Movie.Title) %><br/> Actor Name: <%= Html.TextBoxFor(model=>model.Actor.Name) %> <% } %>

    Read the article

  • Passing viewmodel to actionresult creates new viewmodel

    - by Jonas Bohez
    I am using a viewmodel, which i then when to send to an actionresult to use (the modified viewmodel) But in the controller, i lose the list and objects in my viewmodel. This is my view: @using PigeonFancier.Models @model PigeonFancier.Models.InschrijvingModel @using (Html.BeginForm("UpdateInschrijvingen","Melker",Model)) { <div> <fieldset> <table> @foreach (var item in Model.inschrijvingLijst) { <tr> <td>@Html.DisplayFor(model => item.Duif.Naam)</td> <td> @Html.CheckBoxFor(model => item.isGeselecteerd)</td> </tr> } </table> <input type="submit" value="Wijzigen"/> </fieldset> </div> } This is my controller, which does nothing at the moment until i can get the full viewmodel back from the view. public ActionResult UpdateInschrijvingen(InschrijvingModel inschrijvingsModel) { // inschrijvingsModel is not null, but it creates a new model before it comes here with //Use the model for some updates return RedirectToAction("Inschrijven", new { vluchtId = inschrijvingsModel.vlucht.VluchtId }); } This is the model with the List and some other objects who become null because it creates a new model when it comes back from the view to the actionresult public class InschrijvingModel { public Vlucht vlucht; public Duivenmelker duivenmelker; public List<CheckBoxModel> inschrijvingLijst { get; set; } public InschrijvingModel() { // Without this i get, No parameterless constructor defined exception. // So it uses this when it comes back from the view to make a new model } public InschrijvingModel(Duivenmelker m, Vlucht vl) { inschrijvingLijst = new List<CheckBoxModel>(); vlucht = vl; duivenmelker = m; foreach (var i in m.Duiven) { inschrijvingLijst.Add(new CheckBoxModel(){Duif = i, isGeselecteerd = i.IsIngeschrevenOpVlucht(vl)}); } } What is going wrong and how should i fix this problem please? Thanks

    Read the article

  • Hierarchical View/ViewModel/Presenters in MVPVM

    - by Brian Flynn
    I've been working with MVVM for a while, but I've recently started using MVPVM and I want to know how to create hierarchial View/ViewModel/Presenter app using this pattern. In MVVM I would typically build my application using a hierarchy of Views and corresponding ViewModels e.g. I might define 3 views as follows: The View Models for these views would be as follows: public class AViewModel { public string Text { get { return "This is A!"; } } public object Child1 { get; set; } public object Child2 { get; set; } } public class BViewModel { public string Text { get { return "This is B!"; } } } public class CViewModel { public string Text { get { return "This is C!"; } } } In would then have some data templates to say that BViewModel and CViewModel should be presented using View B and View C: <DataTemplate DataType="{StaticResource local:BViewModel}"> <local:BView/> </DataTemplate> <DataTemplate DataType="{StaticResource local:CViewModel}"> <local:CView/> </DataTemplate> The final step would be to put some code in AViewModel that would assign values to Child1 and Child2: public AViewModel() { this.Child1 = new AViewModel(); this.Child2 = new BViewModel(); } The result of all this would be a screen that looks something like: Doing this in MVPVM would be fairly simple - simply moving the code in AViewModel's constructor to APresenter: public class APresenter { .... public void WireUp() { ViewModel.Child1 = new BViewModel(); ViewModel.Child2 = new CViewModel(); } } But If I want to have business logic for BViewModel and CViewModel I would need to have a BPresenter and a CPresenter - the problem is, Im not sure where the best place to put these are. I could store references to the presenter for AViewModel.Child1 and AViewModel.Child2 in APresenter i.e.: public class APresenter : IPresenter { private IPresenter child1Presenter; private IPresenter child2Presenter; public void WireUp() { child1Presenter = new BPresenter(); child1Presenter.WireUp(); child2Presenter = new CPresenter(); child2Presenter.WireUp(); ViewModel.Child1 = child1Presenter.ViewModel; ViewModel.Child2 = child2Presenter.ViewModel; } } But this solution seems inelegant compared to the MVVM approach. I have to keep track of both the presenter and the view model and ensure they stay in sync. If, for example, I wanted a button on View A, which, when clicked swapped the View's in Child1 and Child2, I might have a command that did the following: var temp = ViewModel.Child1; ViewModel.Child1 = ViewModel.Child2; ViewModel.Child2 = temp; This would work as far as swapping the view's on screen (assuming the correct Property Change notification code is in place), but now my APresenter.child1Presenter is pointing to the presenter for AViewModel.Child2, and APresenter.child2Presenter is pointing to the presenter for AViewModel.Child1. If something accesses APresenter.child1Presenter, any changes will actually happen to AViewModel.Child2. I can imagine this leading to all sorts of debugging fun. I know that I may be misunderstanding the pattern, and if this is the case a clarification of what Im doing wrong would be appreciated.

    Read the article

  • Regarding the ViewModel

    - by mizipzor
    Im struggling to understand the ViewModel part of the MVVM pattern. My current approach is to have a class, with no logic whatsoever (important), except that it implements INotifyPropertyChanged. The class is just a collection of properties, a struct if you like, describing an as small part of the data as possible. I consider this my Model. Most of the WPF code I write are settings dialogs that configure said Model. The code-behind of the dialog exposes a property which returns an instance of the Model. In the XAML code I bind to subproperties of that property, thereby binding directly to the Model's properties. Which works quite well since it implements the INotifyPropertyChanged. I consider this settings dialog the View. However, I havent really been able to figure out what in all this is the ViewModel. The articles Ive read suggests that the ViewModel should tie the View and the Model together, providing the logic the Model lacks but is still to complex to go directly into the View. Is this correct? Would, in my example, the code-behind of the settings dialog be considered the ViewModel? I just feel a bit lost and would like my peers to debunk some of my assumptions. Am I completely off track here?

    Read the article

  • Proper way to validate model in ASP.NET MVC 2 and ViewModel apporach

    - by adrin
    I am writing an ASP.NET MVC 2 application using NHibernate and repository pattern. I have an assembly that contains my model (business entities), moreover in my web project I want to use flattened objects (possibly with additional properties/logic) as ViewModels. These VMs contain UI-specific metadata (eg. DisplayAttribute used by Html.LabelFor() method). The problem is that I don't know how to implement validation so that I don't repeat myself throughout various tiers (specifically validation rules are written once in Model and propagated to ViewModel). I am using DataAnnotations on my ViewModel but this means no validation rules are imposed on the Model itself. One approach I am considering is deriving ViewModel objects from business entities adding new properties/overriding old ones, thus preserving validation metadata between the two however this is an ugly workaround. I have seen Automapper project which helps to map properties, but I am not sure if it can handle ASP.NET MVC 2 validation metadata properly. Is it difficult to use custom validation framework in asp.net mvc 2? Do you have any patterns that help to preserve DRY in regard to validation?

    Read the article

  • ASP.NET MVC ViewModel Pattern

    - by Omu
    EDIT: I made something much better to fill and read data from a view using ViewModels, called it ValueInjecter. http://valueinjecter.codeplex.com/documentation using the ViewModel to store the mapping logic was not such a good idea because there was repetition and SRP violation, but now with the ValueInjecter I have clean ViewModels and dry mapping code I made a ViewModel pattern for editing stuff in asp.net mvc this pattern is usefull when you have to make a form for editing an entity and you have to put on the form some dropdowns for the user to choose some values public class OrganisationViewModel { //paramterless constructor required, cuz we are gonna get an OrganisationViewModel object from the form in the post save method public OrganisationViewModel() : this(new Organisation()) {} public OrganisationViewModel(Organisation o) { Organisation = o; Country = new SelectList(LookupFacade.Country.GetAll(), "ID", "Description", CountryKey); } //that's the Type for whom i create the viewmodel public Organisation Organisation { get; set; } #region DropDowns //for each dropdown i have a int? Key that stores the selected value public IEnumerable<SelectListItem> Country { get; set; } public int? CountryKey { get { if (Organisation.Country != null) { return Organisation.Country.ID; } return null; } set { if (value.HasValue) { Organisation.Country = LookupFacade.Country.Get(value.Value); } } } #endregion } and that's how i use it public ViewResult Edit(int id) { var model = new OrganisationViewModel(organisationRepository.Get(id)); return View(model); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(OrganisationViewModel model) { organisationRepository.SaveOrUpdate(model.Organisation); return RedirectToAction("Index"); } and the markup <p> <label for="Name"> Name:</label> <%= Html.Hidden("Organisation.ID", Model.Organisation.ID)%> <%= Html.TextBox("Organisation.Name", Model.Organisation.Name)%> <%= Html.ValidationMessage("Organisation.Name", "*")%> </p> <p> ... <label for="CountryKey"> Country:</label> <%= Html.DropDownList("CountryKey", Model.Country, "please select") %> <%= Html.ValidationMessage("CountryKey", "*") %> </p> so tell me what you think about it

    Read the article

  • Maintaining ViewModel fields with default model binding and failed validation

    - by TonE
    I have an ASP.Net MVC Controller with a 'MapColumns' action along with a corresponding ViewModel and View. I'm using the defaultModelBinder to bind a number of drop down lists to a Dictionary in the ViewModel. The view model also contains an IList field for both source and destination columns which are used to render the view. My question is what to do when validation fails on the Post call to the MapColumns action? Currently the MapColumns view is returned with the ViewModel resulting from the default binding. This contains the Dictionary values but not the two lists used to render the page. What is the best way to re-provide these to the view? I can set them explicitly after failed validation, but if obtaining these values (via GetSourceColumns() and GetDestinationColumns() in the example) carries any overhead this doesn't seem ideal. What I am looking for is a way to retain these lists when they are not bound to the model from the view. Here is some code to illustrate: public class TestViewModel { public Dictionary<string, string> ColumnMappings { get; set; } public List<string> SourceColumns; public List<string> DestinationColumns; } public class TestController : Controller { [AcceptVerbs(HttpVerbs.Get)] public ActionResult MapColumns() { var model = new TestViewModel; model.SourceColumns = GetSourceColumns(); model.DestinationColumns = GetDestinationColumns(); return View(model); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult MapColumns(TestViewModel model) { if( Validate(model) ) { // Do something with model.ColumnMappings RedirectToAction("Index"); } else { // Here model.SourceColumns and model.DestinationColumns are empty return View(model); } } } The relevant section of MapColumns.aspx: <% int columnCount = 0; foreach(string column in Model.targetColumns) {%> <tr> <td> <input type="hidden" name="ColumnMappings[<%= columnCount %>].Value" value="<%=column %>" /> <%= Html.DropDownList("ColumnMappings[" + columnCount + "].Key", Model.DestinationColumns.AsSelectItemList())%> </td> </tr> <% columnCount++; }%>

    Read the article

  • How reusable should ViewModel classes be?

    - by stiank81
    I'm working on a WPF application, and I'm structuring it using the MVVM pattern. Initially I had an idea that the ViewModels should be reusable, but now I'm not too sure anymore. Should I be able to reuse my ViewModels if I need similar functionality for a WinForms application? Silverlight doesn't support all things WPF does - should I be able to reuse for Silverlight applications? What if I want to make a Linux GUI for my application. Then I need the ViewModel to build in Mono - is this something I should strive for? And so on.. So; should one write ViewModel classes with one specific View in mind, or think of reusability?

    Read the article

  • Where and how to validate and map ViewModel?

    - by chobo
    Hi, I am trying to learn Domain Driven Design and recently read that lots of people advocate creating a ViewModels for your views that store all the values you want to display in a given view. My question is how should I do the form validation? should I create separate validation classes for each view, or group them together? I'm also confused on what this would look like in code. This is how I currently think validation and viewmodels fit in to the scheme of things: View (some user input) - Controller - FormValidation(of ViewModel) - (If valid map to ViewModel to Domain Model) - Domain Layer Service - Infrastructure Thanks! P.S. I use Asp.net MVC with C#

    Read the article

  • ViewModel with SelectList binding in ASP.NET MVC2

    - by Junto
    I am trying to implement an Edit ViewModel for my Linq2SQL entity called Product. It has a foreign key linked to a list of brands. Currently I am populating the brand list via ViewData and using DropDownListFor, thus: <div class="editor-field"> <%= Html.DropDownListFor(model => model.BrandId, (SelectList)ViewData["Brands"])%> <%= Html.ValidationMessageFor(model => model.BrandId) %> </div> Now I want to refactor the view to use a strongly typed ViewModel and Html.EditorForModel(): <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%=Html.EditorForModel() %> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> In my Edit ViewModel, I have the following: public class EditProductViewModel { [HiddenInput] public int ProductId { get; set; } [Required()] [StringLength(200)] public string Name { get; set; } [Required()] [DataType(DataType.Html)] public string Description { get; set; } public IEnumerable<SelectListItem> Brands { get; set; } public int BrandId { get; set; } public EditProductViewModel(Product product, IEnumerable<SelectListItem> brands) { this.ProductId = product.ProductId; this.Name = product.Name; this.Description = product.Description; this.Brands = brands; this.BrandId = product.BrandId; } } The controller is setup like so: public ActionResult Edit(int id) { BrandRepository br = new BrandRepository(); Product p = _ProductRepository.Get(id); IEnumerable<SelectListItem> brands = br.GetAll().ToList().ToSelectListItems(p.BrandId); EditProductViewModel model = new EditProductViewModel(p, brands); return View("Edit", model); } The ProductId, Name and Description display correctly in the generated view, but the select list does not. The brand list definitely contains data. If I do the following in my view, the SelectList is visible: <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%=Html.EditorForModel() %> <div class="editor-label"> <%= Html.LabelFor(model => model.BrandId) %> </div> <div class="editor-field"> <%= Html.DropDownListFor(model => model.BrandId, Model.Brands)%> <%= Html.ValidationMessageFor(model => model.BrandId) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> What am I doing wrong? Does EditorForModel() not generically support the SelectList? Am I missing some kind of DataAnnotation? I can't seem to find any examples of SelectList usage in ViewModels that help. I'm truly stumped. This answer seems to be close, but hasn't helped.

    Read the article

  • Using ViewModel in ASP.NET MVC with FluentValidation

    - by Brian McCord
    I am using ASP.NET MVC with Entity Framework POCO classes and the FluentValidation framework. It is working well, and the validation is happening as it should (as if I were using DataAnnotations). I have even gotten client-side validation working. And I'm pretty pleased with it. Since this is a test application I am writing just to see if I can get new technologies working together (and learn them along the way), I am now ready to experiment with using ViewModels instead of just passing the actual Model to the view. I'm planning on using something like AutoMapper in my service to do the mapping back and forth from Model to ViewModel but I have a question first. How is this going to affect my validation? Should my validation classes (written using FluentValidation) be written against the ViewModel instead of the Model? Or does it need to happen in both places? One of the big deals about DataAnnotations (and FluentValidation) was that you could have validation in one place that would work "everywhere". And it fulfills that promise (mostly), but if I start using ViewModels, don't I lose that ability and have to go back to putting validation in two places? Or am I just thinking about it wrong?

    Read the article

  • How to handle One View with multiple ViewModel and fire different Commands

    - by Naresh
    Hi All, I have senario in which one view and view has binding with multiple ViewModel. Eg. One View displaying Phone Detail and ViewModel as per bellow: Phone basic features- PhoneViewModel, Phone Price Detail- PhoneSubscriptionViewModel, Phone Accessories- PhoneAccessoryViewModel For general properties- PhoneDetailViewModel I have placed View's general properties to PhoneViewModel.Now senario is like this: By default View displays Phone Basic feaures which is bind with ObservationCollection of PhoneViewModel. My view have button - 'View Accessories', onclick of this button one popup screen- in my design I have display/hide Grid and bind it with ObservationCollection of PhoneAccessoryViewModel. Now problem begins- Accessory List also have button 'View Detail' onclick I have to open one popup screen, here also I had placed one Grid and Visible/Hide it. I have bind 'ViewAccessoryDetailCommand' command to 'View Detail' button. And on command execution one function fires and set property which Visible the Popup screen. Using such programming command fires, function calls but the property change not raises and so my view does not display popup. Summary: One View-- ViewModel1--Grid Bind view ViewModel2 --Grid Have Button and Onclick display new Grid which binded with ViewModel3-this Command fires but property not raises. I think there is some problem in my methodology, Please, give your suggetions.

    Read the article

  • How to use a Base ViewModel in Asp.net MVC 2

    - by Picflight
    As I familiarize myself with Asp.Net MVC, I am using MVC 2, I have noticed the use of a BaseViewData class in the Kigg project which I am unsure how to implement. I want each of my ViewModels to have certain values available. Using an iterface comes to mind but I am wondering what the best practice is and how does Kigg do it? Kigg public abstract class BaseViewData { public string SiteTitle { get; set; } // ...other properties } public class UserListViewData : BaseViewData { public string Title { get; set; } // .. other stuff } In my WebForms application I use a BasePage that inherits from System.Web.UI.Page. So, in my MVC project, I have this: public abstract class BaseViewModel { public int SiteId { get; set; } } public class UserViewModel : BaseViewModel { // Some arbitrary ViewModel } Referencing the Kigg methodology, how do I make sure that each of my ViewModel that inherits from the BaseViewModel have the SiteId property? What is the best practice, samples or patterns I should be using?

    Read the article

  • ASP.MVC 1.0 complex ViewModel not populating on Action

    - by Graham
    Hi, I'm 3 days into learning MVC for a new project and i've managed to stumble my way over the multitude of issues I've come across - mainly about something as simple as moving data to a view and back into the controller in a type-safe (and manageable) manner. This is the latest. I've seen this reported before but nothing advised has seemed to work. I have a complex view model: public class IndexViewModel : ApplicationViewModel { public SearchFragment Search { get; private set; } public IndexViewModel() { this.Search = new SearchFragment(); } } public class SearchFragment { public string ItemId { get; set; } public string Identifier { get; set; } } This maps to (the main Index page): %@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IndexViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <% Html.BeginForm("Search", AvailableControllers.Search, FormMethod.Post); %> <div id="search"> <% Html.RenderPartial("SearchControl", Model.Search); %> </div> <% Html.EndForm(); %> </asp:Content> and a UserControl: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SearchFragment>" %> <p> <label for="itemId"> <%= Html.Resource("ItemId") %></label> <%= Html.TextBox("itemId", Model.ItemId)%> </p> <p> <label for="title"> <%= Html.Resource("Title") %></label> <%= Html.TextBox("identifier", Model.Identifier)%> </p> <p> <input type="submit" value="<%= Html.Resource("Search") %>" name="search" /> </p> This is returned to the following method: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Search(IndexViewModel viewModel) { .... } My problem is that when the view model is rehydrated from the View into the ViewModel, the SearchFragment elements are null. I suspect this is because the default model binder doesn't realise the HTML ItemId and Identifier elements rendered inline in the View map to the SearchFragment class. When I have two extra properties (ItemId and Identifier) in the IndexViewModel, the values are bound correctly. Unfortunately, as far as I can tell, I must use the SearchFragment as I need this to strongly type the Search UserControl... as the control can be used anywhere it can operate under any parent view. I really don't want to make it use "magic strings". There's too much of that going on already IMO. I've tried prefixing the HTML with "Search." in the hope that the model binder would recognise "Search.ItemId" and match to the IndexViewModel "Search" property and the ItemId within it, but this doesn't work. I fear I'm going to have to write my own ModelBinder to do this, but surely this must be something you can do out-of-the-box?? Failing that is there any other suggestions (or link to someone who has already done this?) Here's hoping....

    Read the article

  • Dynamic/Generic ViewModelBase?

    - by Shimmy
    I am learning MVVM now and I understand few things (more than but few are here..): Does every model potentially exposed (thru a VM) to the View is having a VM? For example, if I have a Contact and Address entity and each contact has an Addresses (many) property, does it mean I have to create a ContactViewModel and an AddressViewModel etc.? Do I have to redeclare all the properties of the Model again in the ViewModel (i.e. FirstName, LastName blah blah)? why not have a ViewModelBase and the ContactViewMode will be a subclass of ViewModelBase accessing the Entity's properties itself? and if this is a bad idea that the View has access to the entity (please explain why), then why not have the ViewModelBase be a DynamicObject (view the Dictionary example @ the link page), so I don't have to redeclare all the properties and validation over and over in the two tiers (M & VM) - because really, the View is anyway accessing the ViewModel's fields via reflection anyway. I think MVVM was the hardest technology I've ever learned. it doesn't have out-the-box support and there are to many frameworks and methods to achieve it, and in the other hand there is no arranged way to learn it (as MVC for instance), learning MVVM means browsing and surfing around trying to figure out what's better. Bottom line, what I mean by this section is please go and vote to MSFT to add MVVM support in the BCL and generators for VMs and Vs according to the Ms. Thanks

    Read the article

  • Adventures in MVVM &ndash; My ViewModel Base

    - by Brian Genisio's House Of Bilz
    More Adventures in MVVM First, I’d like to say: THIS IS NOT A NEW MVVM FRAMEWORK. I tend to believe that MVVM support code should be specific to the system you are building and the developers working on it.  I have yet to find an MVVM framework that does everything I want it to without doing too much.  Don’t get me wrong… there are some good frameworks out there.  I just like to pick and choose things that make sense for me.  I’d also like to add that some of these features only work in WPF.  As of Silveright 4, they don’t support binding to dynamic properties, so some of the capabilities are lost. That being said, I want to share my ViewModel base class with the world.  I have had several conversations with people about the problems I have solved using this ViewModel base.  A while back, I posted an article about some experiments with a “Rails Inspired ViewModel”.  What followed from those ideas was a ViewModel base class that I take with me and use in my projects.  It has a lot of features, all designed to reduce the friction in writing view models. I have put the code out on Codeplex under the project: ViewModelSupport. Finally, this article focuses on the ViewModel and only glosses over the View and the Model.  Without all three, you don’t have MVVM.  But this base class is for the ViewModel, so that is what I am focusing on. Features: Automatic Command Plumbing Property Change Notification Strongly Typed Property Getter/Setters Dynamic Properties Default Property values Derived Properties Automatic Method Execution Command CanExecute Change Notification Design-Time Detection What about Silverlight? Automatic Command Plumbing This feature takes the plumbing out of creating commands.  The common pattern for commands in a ViewModel is to have an Execute method as well as an optional CanExecute method.  To plumb that together, you create an ICommand Property, and set it in the constructor like so: Before public class AutomaticCommandViewModel { public AutomaticCommandViewModel() { MyCommand = new DelegateCommand(Execute_MyCommand, CanExecute_MyCommand); } public void Execute_MyCommand() { // Do something } public bool CanExecute_MyCommand() { // Are we in a state to do something? return true; } public DelegateCommand MyCommand { get; private set; } } With the base class, this plumbing is automatic and the property (MyCommand of type ICommand) is created for you.  The base class uses the convention that methods be prefixed with Execute_ and CanExecute_ in order to be plumbed into commands with the property name after the prefix.  You are left to be expressive with your behavior without the plumbing.  If you are wondering how CanExecuteChanged is raised, see the later section “Command CanExecute Change Notification”. After public class AutomaticCommandViewModel : ViewModelBase { public void Execute_MyCommand() { // Do something } public bool CanExecute_MyCommand() { // Are we in a state to do something? return true; } }   Property Change Notification One thing that always kills me when implementing ViewModels is how to make properties that notify when they change (via the INotifyPropertyChanged interface).  There have been many attempts to make this more automatic.  My base class includes one option.  There are others, but I feel like this works best for me. The common pattern (without my base class) is to create a private backing store for the variable and specify a getter that returns the private field.  The setter will set the private field and fire an event that notifies the change, only if the value has changed. Before public class PropertyHelpersViewModel : INotifyPropertyChanged { private string text; public string Text { get { return text; } set { if(text != value) { text = value; RaisePropertyChanged("Text"); } } } protected void RaisePropertyChanged(string propertyName) { var handlers = PropertyChanged; if(handlers != null) handlers(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } This way of defining properties is error-prone and tedious.  Too much plumbing.  My base class eliminates much of that plumbing with the same functionality: After public class PropertyHelpersViewModel : ViewModelBase { public string Text { get { return Get<string>("Text"); } set { Set("Text", value);} } }   Strongly Typed Property Getters/Setters It turns out that we can do better than that.  We are using a strongly typed language where the use of “Magic Strings” is often frowned upon.  Lets make the names in the getters and setters strongly typed: A refinement public class PropertyHelpersViewModel : ViewModelBase { public string Text { get { return Get(() => Text); } set { Set(() => Text, value); } } }   Dynamic Properties In C# 4.0, we have the ability to program statically OR dynamically.  This base class lets us leverage the powerful dynamic capabilities in our ecosystem. (This is how the automatic commands are implemented, BTW)  By calling Set(“Foo”, 1), you have now created a dynamic property called Foo.  It can be bound against like any static property.  The opportunities are endless.  One great way to exploit this behavior is if you have a customizable view engine with templates that bind to properties defined by the user.  The base class just needs to create the dynamic properties at runtime from information in the model, and the custom template can bind even though the static properties do not exist. All dynamic properties still benefit from the notifiable capabilities that static properties do. For any nay-sayers out there that don’t like using the dynamic features of C#, just remember this: the act of binding the View to a ViewModel is dynamic already.  Why not exploit it?  Get over it :) Just declare the property dynamically public class DynamicPropertyViewModel : ViewModelBase { public DynamicPropertyViewModel() { Set("Foo", "Bar"); } } Then reference it normally <TextBlock Text="{Binding Foo}" />   Default Property Values The Get() method also allows for default properties to be set.  Don’t set them in the constructor.  Set them in the property and keep the related code together: public string Text { get { return Get(() => Text, "This is the default value"); } set { Set(() => Text, value);} }   Derived Properties This is something I blogged about a while back in more detail.  This feature came from the chaining of property notifications when one property affects the results of another, like this: Before public class DependantPropertiesViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); RaisePropertyChanged("Percentage"); RaisePropertyChanged("Output"); } } public int Percentage { get { return (int)(100 * Score); } } public string Output { get { return "You scored " + Percentage + "%."; } } } The problem is: The setter for Score has to be responsible for notifying the world that Percentage and Output have also changed.  This, to me, is backwards.    It certainly violates the “Single Responsibility Principle.” I have been bitten in the rear more than once by problems created from code like this.  What we really want to do is invert the dependency.  Let the Percentage property declare that it changes when the Score Property changes. After public class DependantPropertiesViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); } } [DependsUpon("Score")] public int Percentage { get { return (int)(100 * Score); } } [DependsUpon("Percentage")] public string Output { get { return "You scored " + Percentage + "%."; } } }   Automatic Method Execution This one is extremely similar to the previous, but it deals with method execution as opposed to property.  When you want to execute a method triggered by property changes, let the method declare the dependency instead of the other way around. Before public class DependantMethodsViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); WhenScoreChanges(); } } public void WhenScoreChanges() { // Handle this case } } After public class DependantMethodsViewModel : ViewModelBase { public double Score { get { return Get(() => Score); } set { Set(() => Score, value); } } [DependsUpon("Score")] public void WhenScoreChanges() { // Handle this case } }   Command CanExecute Change Notification Back to Commands.  One of the responsibilities of commands that implement ICommand – it must fire an event declaring that CanExecute() needs to be re-evaluated.  I wanted to wait until we got past a few concepts before explaining this behavior.  You can use the same mechanism here to fire off the change.  In the CanExecute_ method, declare the property that it depends upon.  When that property changes, the command will fire a CanExecuteChanged event, telling the View to re-evaluate the state of the command.  The View will make appropriate adjustments, like disabling the button. DependsUpon works on CanExecute methods as well public class CanExecuteViewModel : ViewModelBase { public void Execute_MakeLower() { Output = Input.ToLower(); } [DependsUpon("Input")] public bool CanExecute_MakeLower() { return !string.IsNullOrWhiteSpace(Input); } public string Input { get { return Get(() => Input); } set { Set(() => Input, value);} } public string Output { get { return Get(() => Output); } set { Set(() => Output, value); } } }   Design-Time Detection If you want to add design-time data to your ViewModel, the base class has a property that lets you ask if you are in the designer.  You can then set some default values that let your designer see what things might look like in runtime. Use the IsInDesignMode property public DependantPropertiesViewModel() { if(IsInDesignMode) { Score = .5; } }   What About Silverlight? Some of the features in this base class only work in WPF.  As of version 4, Silverlight does not support binding to dynamic properties.  This, in my opinion, is a HUGE limitation.  Not only does it keep you from using many of the features in this ViewModel, it also keeps you from binding to ViewModels designed in IronRuby.  Does this mean that the base class will not work in Silverlight?  No.  Many of the features outlined in this article WILL work.  All of the property abstractions are functional, as long as you refer to them statically in the View.  This, of course, means that the automatic command hook-up doesn’t work in Silverlight.  You need to plumb it to a static property in order for the Silverlight View to bind to it.  Can I has a dynamic property in SL5?     Good to go? So, that concludes the feature explanation of my ViewModel base class.  Feel free to take it, fork it, whatever.  It is hosted on CodePlex.  When I find other useful additions, I will add them to the public repository.  I use this base class every day.  It is mature, and well tested.  If, however, you find any problems with it, please let me know!  Also, feel free to suggest patches to me via the CodePlex site.  :)

    Read the article

  • ASP.NET MVC: what mechanic returns ViewModel objects?

    - by Dr. Zim
    As I understand it, Domain Models are classes that only describe the data (aggregate roots). They are POCOs and do not reference outside libraries (nothing special). View models on the other hand are classes that contain domain model objects as well as all the interface specific objects like SelectList. A ViewModel includes using System.Web.Mvc;. A repository pulls data out of a database and feeds them to us through domain model objects. What mechanic or device creates the view model objects, populating them from a database? Would it be a factory that has database access? Would you bleed the view specific classes like System.Web.Mvc in to the Repository? Something else? For example, if you have a drop down list of cities, you would reference a SelectList object in the root of your View Model object, right next to your DomainModel reference: public class CustomerForm { public CustomerAddress address {get;set;} public SelectList cities {get;set;} } The cities should come from a database and be in the form of a select list object. The hope is that you don't create a special Repository method to extract out just the distinct cities, then create a redundant second SelectList object only so you have the right data types.

    Read the article

  • Manipulating collections & the ViewModel pattern

    - by Kragen
    I'm relatively new to WPF, and I'm having trouble with what I'm fairly certain is a relatively simple problem. I have my underlying data object, a Person: class Person { public string Surname {get; set; } public string Firstname {get; set; } public List<Address> Addresses {get; } } And I wish to display and edit this object in my WPF app. To this end I've created a ViewModel that I bind to in my xaml: class PersonViewModel { public string Fullname {get; } public ObservableCollection<AddressViewModel> Addresses {get; } } This is fine, except when it comes to manipulating my Address collection, where I can't work out what I should be doing: Should I add methods AddAddress, RemoveAddress etc... to my PersonViewModel class for manipulating my collection with instances of AddressViewModel Should I just add instances of AddressViewModel to my Addresses observable collection Both of the above seem a bit messy - is there a better way of dealing with collections?

    Read the article

  • ViewModel Views relation/link/syncroniztion

    - by mehran
    Third try to describing problem: Try 1: Sunchronizing view model and view Try2: WPF ViewModel not active presenter Try3: I have some class for view models: public class Node : INotifyPropertyChanged { Guid NodeId { get; set; } public string Name { get; set; } } public class Connection: INotifyPropertyChanged { public Node StartNode { get; set; } public Node EndNode { get; set; } } public class SettingsPackModel { public List<Node> Nodes { get; private set; } public List<Connection> Connections { get; private set; } } I also have some templates to displays these models: <DataTemplate DataType="{x:Type vm:Node}">…</DataTemplate> <DataTemplate DataType="{x:Type vm:Connection}"> <my:ConnectionElment StartNodeElment="???" EndNodeElment="???"> </my:ConnectionElment> <DataTemplate> But the problem is that DataTemplate for Connection need reference ot two element of type UIElement , how can I pass these two, how can I fill ??? in above expression?

    Read the article

  • View/ViewModel Interaction - Bindings, Commands and Triggers

    It looks like I have a set of posts on ViewModel, aka MVVM, that have organically emerged into a series or story of sorts. Recently, I blogged about The Case for ViewModel, and another on View/ViewModel Association using Convention and Configuration, and a long while back now, I posted an Introduction to the ViewModel Pattern as I was myself picking up this pattern, which has since become the natural way for me to program client applications. This installment adds to this on-going series. I've...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

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >