Search Results

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

Page 27/36 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • How do I know if a drag/drop has been cancelled in WPF

    - by Jon Mitchell
    I'm writing a user control in WPF which is based on a ListBox. One of the main pieces of functionality is the ability to reorder the list by dragging the items around. When a user drags an item I change the items Opacity to 50% and physically move the item in an ObservableCollection in my ViewModel depending on where the user wants it. On the drop event I change the Opacity back to 100%. The problem I've got is that if the user drags the item off my control and drops it somewhere else then I need to change the Opacity back to 100% and move the item back to where it was when the user started the drag. Is there an event I can handle to capture this action? If not is there any other cunning way to solve this problem?

    Read the article

  • WPF TextBox value doesn't change on OnPropertyChanged

    - by jpsstavares
    I have a TextBox whose Value is binded to a ViewModel property: <TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding Mode=TwoWay, Path=RunAfter}" Style="{StaticResource TestStepTextBox}"/> The set and get were working fine until I tried to add some validation when the Value is set: private int _runAfter = 0; public string RunAfter { get { return _runAfter.ToString(); } set { int val = int.Parse(value); if (_runAfter != val) { if (val < _order) _runAfter = val; else { _runAfter = 0; OnPropertyChanged("RunAfter"); } } } } Although the OnPropertyChanged is reached (I have dubugged that), the View is not changed. How can I make this work? Thanks, José Tavares

    Read the article

  • how to get TabHeader on trigger

    - by CurlyFro
    i have a tabcontrol. i'm trying to pass the tabcontrol as a parameter to figure out the selected tab item so i can get the tab header name. Binding this doesn't seem to work. ideas? <TabControl Background="#FFF9F9F9" Height="650"> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <n:ExecuteCommandAction Command="{Binding UpdateTabCommand}" Parameter="{Binding this}"/> </i:EventTrigger> </i:Interaction.Triggers> in my viewmodel constructor i have: _updateTabCommand = new ActionCommand< TabControl>(UpdateTab); private method: public void UpdateTab(TabControl tabControl) { var tabItem = (TabItem)tabControl.SelectedItem;

    Read the article

  • How to call/use a value converter inverted

    - by Soko
    Is it possible to use a converter the "wrong" way around? In other words: can I swap source and target? Here's an example: I created a simple IValueConverter called NullableDecimalToStringConverter which converts an input if "" into null and a number into decimal. I use it to bind a TextBox in my WPF view to a decimal? property in my ViewModel. In another context I'd like to convert a NullableDecimal into a String in the same way... Is it possible to simply use the existing NullableDecimalToStringConverter inverted? One method is to use the parameter of the converter to tell the converter which way it should convert. But is there a .NET build in way to do such a thing? Another way would be to build a base class with both conversion methods and two separate converter which call the base class methods...

    Read the article

  • How to read a complex view model on POST?

    - by Interfector
    Hello, I have an user view model that has the following properties: public User user; public List<Language> Languages; I send the above model to the view and use html helpers to build the form, so I end up with something like: <form action="/Users/Edit/5" method="post"><input id="user_UserId" name="user.UserId" type="hidden" value="5" /> First Name Last Name Email Language - en en Now, I try to read the POST in something that initially was something like : [AcceptVerbs( HttpVerbs.Post )] public ActionResult Edit( int UserId, FormCollection form ) { and cannot get the user.UserId variable, user.FirstName variable etc. Any idea what needs to be done to be able to read this kind of POST request. I'm kind of reluctant to modifying my ViewModel as it is very simple and easy to maintain as it is. Thank you.

    Read the article

  • any ideas for avoiding duplicate code in C# and javascript

    - by ooo
    i have an asp.net mvc website where i build up most of the page using C# for example building up html tables given a set of data from my viewmodel i also have a lot of javascript that then dynamcially modifies these tables (add row for example). the javascript code to add a new row looks extremely similar to my "rendering" code i have in C# that is used to build up the html table in the first place. Every time i change the c# code to a add a new field, i have to remember to go back to the javascript code to do the same. is there a better way here?

    Read the article

  • WPF ComboBox Binding + Selected Index for object.

    - by abmv
    I have a case of WPF binding I want to solve: The issue is that I have a user detail screen and it has a employee combo box that gets filled with employees. cbxEmployee.ItemsSource = DataAccess.GetCollectionView("Employee", "[Active] = True", viewModel.Context); cbxEmployee.DisplayMemberPath = "FullName"; cbxEmployee.SelectedValuePath = "ID"; The binding in user detail screen xaml is for the user object, I just need the employee id to store in the int property.So no problems when the user selects an employee. <ComboBox x:Name="cbxEmployee" SelectedItem="{Binding Path=Employee,ValidatesOnExceptions=True}" SelectedValue="{Binding Path=AssociatedEmployeeId}" Style="{DynamicResource InputBaseStyle}"/> Now the issue is that when an existing object is edited I need the combo box to get the correct employee to be shown,i.e the index should be set at the correct employee for the AssociatedEmployeeId of the user object. Well how the heck should I do it ? Any advice?

    Read the article

  • RelayCommands overriding the "IsEnabled" of my buttons.

    - by vidalsasoon
    RelayCommands overriding the "IsEnabled" of my buttons. Is this is a bug? Here is xaml from my View and code from my ViewModel <Button Grid.Column="0" Content="Clear" IsEnabled="False" cmd:ButtonBaseExtensions.Command="{Binding ClearCommand}" /> public RelayCommand ClearCommand { get { return new RelayCommand(() => MessageBox.Show("Clear Command")); } } Notice I hardcoded the IsEnabled="False" in my xaml. This value is completely ignored (button always enabled). I realize that RelayCommand have a CanExecute overload but I did want to use this as I want to do more than just have a disabled button.

    Read the article

  • DataTemplate / ContentTemplate - exchange controls

    - by Scott Olson
    How can i solve the following (simplified) problem? M-V-VM context. I want to show text at the UI. In case the user has the rights to change the text, i want to use a textbox to manipulate the text. In case the user has no rights, i want to use a label to only show the text. My main problem: how to exchange textbox and label and bind Text resp. Content to the same property in viewmodel. Thanks for your answers Toni

    Read the article

  • ASP MVC html helpers in partial views

    - by Rabbi
    I am still trying to figure out how to create reusable partial views in MVC Lets say I would like to create a partial view to display a form for submitting an address. Then in my ViewModel I have two addresses (Home address & Work Address) So I would think that in my view I call HTML.Partial for each one like this @Html.Partial("Address", Model.HomeAddress) @Html.Partial("Address", Model.WorkAddress) but what happens is instead of the fields having names like HomeAddress.Street, HomeAddress.City etc. they just have the regular field names Street, City, etc. so the binder on the HTTPPost action has no idea what to do with them Thanks in advance

    Read the article

  • Mvc3 IEnumerable<QuestionModel> have a List<QuestionOptionModel> property. When I post, I get null list

    - by user1649439
    There is a example here. I am trying to use this technique in a large form with a list(List) but when I post back, the Viewmodel.Order that should’ve contained list of items and activities return with the lists empty. My QuestionModel.cs like this. public int Id { get; set; } public string QuestionText { get; set; } public System.Nullable<bool> OptionType1 { get; set; } public System.Nullable<bool> OptionType2 { get; set; } public List<QuestionOptionModel> OptionList = new List<QuestionOptionModel>(); When I post back "IEnumerable questions" List OptionList comes null. How can I do this?

    Read the article

  • WPF Prism deactivate ?

    - by 2Fast4YouBR
    Hi all, I have an problem and would like to know if it is common problem or jsut with me. I am using Wpf with Prism and Unity, all with the pattern MvvM. I am loading a viewModel that has a reference to a dropdown with few items, my idea is that each time that the user click in some place to open the view that has this dropdown is that the dropdown will be shown with diferent values. The problem is that I see is that after I show the view for the first time and after the first DEACTIVATE, when I try to load it again looks like it is already in the memory (was not deactivated/disposed), so as is already in memory, it not call the constructor again of the modelView and the dropdown is shown with tha same old values. public BranchSelectionViewModel(IUnityContainer unityContainer) { this.unityContainer = unityContainer; User user = this.unityContainer.Resolve<User>(); this.branches = new ObservableCollection<Department>(user.Departments .Where(department => department.DepartmentId != user.SelectedDepartment.DepartmentId)); }

    Read the article

  • ASP.NET MVC Access model data in masterpage

    - by Paul
    I have created a UserSiteBaseController that gets commonly used data and sets the data to a UserSiteBaseViewData viewmodel in a method called SetViewData public T CreateViewData<T>() where T : UserSiteBaseViewData, new() { .... } I then create specific Controllers that inherit from the UserSiteBaseController as well as viewModels that inherit from UserSiteHomeViewData and can be created in the controller like so: public ActionResult Index(string slug) { Slug = slug; var viewData = CreateUserSiteHomeViewData<UserSiteHomeViewData>(); //If invalid slug - throw 404 not found if (viewData == null) return PageNotFound(); viewData.Announcements = _announcementsData.All(slug).ToList(); return View(viewData); } private T CreateUserSiteHomeViewData<T>() where T : UserSiteHomeViewData, new() { T viewData = CreateViewData<T>(); return viewData; } The UserBaseViewData holds data that needs to be use on every page so it would be great to be able to access this data from the Masterpage in a strongly typed manner. Is this possible or am I going about this in the incorrect manner?

    Read the article

  • Creating a System.Windows.Controls.Image throws an exception - how do I use the dispatcher to instan

    - by Scott Whitlock
    I'm running my unit tests on a piece of code that does the following in the test: Assert.IsNotNull(target.Icon); Inside the getter for the Icon property, I'm doing this: System.Windows.Controls.Image img = new System.Windows.Controls.Image(); That's throwing this exception: System.InvalidOperationException : The calling thread must be STA, because many UI components require this. I understand what that means, and I understand that I need to use the Dispatcher, but I'm a bit confused about how or why... this is a property of my ViewModel and I don't get any of these exceptions when running the application. Other info: this only started failing when I upgraded to .NET 4.

    Read the article

  • 2 ajax forms on the same page posting same textbox

    - by rod
    Hi All, Is it possible to post, say like a value in a textbox, to 2 different ajax forms that are on the same page? It doesn't have to be at the same time? What I'm trying to do is this: I have a search page that searches for customers and displays them on a paged grid. Users can specify up to 5 parameters (5 textboxes) to narrow the search. On the same page I have an export option. Well since I want all the customers for the search and not just the paged data I need a way to post back to the server for this option passing the same parameters used in the grid. I'm using a ViewModel which would be nice if I can pass that back to the server rather than the individual search fields that are backed by the view model. Thanks, rodchar

    Read the article

  • Disable Adding Item to Collection

    - by Wonko the Sane
    Hi All, I'm sure there's an "easy" answer to this, but for the moment it escapes me. In an MVVM application, I have a property that is a ObservableCollection, used for displaying some set of elements on the view. private readonly ObservableCollection<MyType> mMyCollection = new ObservableCollection<MyType>(); public ObservableCollection<MyType> MyCollection { get { return mMyCollection; } } I want to restrict consumers of this collection from simply using the property to add to the collection (i.e. I want to prevent this from the view): viewModel.MyCollection.Add(newThing); // want to prevent this! Instead, I want to force the use of a method to add items, because there may be another thread using that collection, and I don't want to modify the collection while that thread is processing it. public void AddToMyCollection(MyType newItem) { // Do some thread/task stuff here } Thanks, wTs

    Read the article

  • WPF/C# - Sometimes my dropdowns/datepickers will stop functioning?

    - by BlargINC
    Q: Where should I check to track this down? Issue: Opening a view model in my application sometimes makes dropdowns/datepickers nonfunctional. ie. dropdown won't drop and the datepicker calendar won't come up I suspect a binding issue but don't see one. Dropdowns have normal things like strings, numbers. One drop has a list of mini views. Datepickers are bound to nullable dates set in the constructor of the viewmodel. Note: These same things work in other viewmodels/views. I can paste code, I'm just not sure what code is relevant here. Thank you for helping me :)

    Read the article

  • Sometimes my dropdowns/datepickers will stop functioning?

    - by BlargINC
    Q: Where should I check to track this down? Issue: Opening a view model in my application sometimes makes dropdowns/datepickers nonfunctional. ie. dropdown won't drop and the datepicker calendar won't come up I suspect a binding issue but don't see one. Dropdowns have normal things like strings, numbers. One drop has a list of mini views. Datepickers are bound to nullable dates set in the constructor of the viewmodel. Note: These same things work in other viewmodels/views. I can paste code, I'm just not sure what code is relevant here.

    Read the article

  • Setting an attribute property to the type of the decorated class.

    - by cmaduro
    Is it possible to get the decorated class' type inside of the custom attribute's class? For example: [MetadataAttribute] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)] public class ViewAttribute : ExportAttribute { public object TargetRegion { get; set; } public Type ViewModel { get; set; } public Type Module { get; set; } public ViewAttribute() : base(typeof(UserControl)) { Module = GetDecoratedClassType(); //I need this method } } In the following example GetDecoratedClassType() would return HomeView [View] HomeView MyHomeView { get; set; }

    Read the article

  • Silverlight Cream for May 02, 2010 -- #854

    - by Dave Campbell
    In this Issue: Michael Washington, Jason Young(-2-, -3-), Phil Middlemiss, Jeremy Likness, Victor Gaudioso, Kunal Chowdhury, Antoni Dol, and Jacek Ciereszko(-2-). Shoutout: Victor Gaudioso has aggregated All of My Silverlight Video Tutorials in One Place (revised again 05.02.10) From SilverlightCream.com: Unit Testing A Silverlight 'Simplified MVVM' Modal Popup Michael Washington's latest 'Simplified MVVM' post is published at The Code Project and is on Unit Testing with MVVM. Input Localization in Silverlight without IValueConverter Jason Young sent me some links to posts I've not seen... this first one is on localization by using the Language property of the Root Visual. MVVM – The Model - Part 1 – INotifyPropertyChanged Jason Young's next archive post is the first of a series on MVVM and Silverlight 4 ... implementing a simple ViewModel base class. Silverlight, WCF, and ASP.Net Configuration Gotchas Jason Young worked at tracking down the answers to some forum questions and in the process has produced a post of 'gotchas' with using WCF in Silverlight. A Chrome and Glass Theme - Part 5 Phil Middlemiss has part 5 of his Chrome and Glass Theme tutorial up ... in this one, he's looking at the Progress Bar and Slider. Download the files and play along. Silverlight Out of Browser (OOB) Versions, Images, and Isolated Storage Jeremy Likness has a post up responding to his 3 major questions about OOB apps, and he has to code up for the sample too. New Silverlight Video Tutorial: How to Make a Slide In/Out Navigation Bar – All in Blend Victor Gaudioso's latest video tutorial is on building a Behavior for a Slide in/out Navigation bar... kinda like the menu sliders on my GlyphMap Utility... only easier! Command Binding in Silverlight 4 (Step-by-Step) Kunal Chowdhury has another post up at DotNetFunda, and this time he's talking about Command Binding in Silverlight 4 with an eye toward MVVM usage. The Silverlight PageCurl implementation Antoni Dol has a post up about doing a Page Curl effect in Silverlight. He has a manual up on the effect and full application code. How to center and scale Silverlight applications using ViewBox control Jacek Ciereszko has a couple posts up about centering and scaling your app with the ViewBox control. This first one is a code solution. Source is available, as is a Polish version. Silverlight Center And Scale Behavior Jacek Ciereszko's 2nd post, he provides a Behavior that handles the scaling and centering of the previous post. 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

  • Silverlight Cream for April 02, 2010 -- #828

    - by Dave Campbell
    In this Issue: Phil Middlemiss, Robert Kozak, Kathleen Dollard, Avi Pilosof, Nokola, Jeff Wilcox, David Anson, Timmy Kokke, Tim Greenfield, and Josh Smith. Shoutout: SmartyP has additional info up on his WP7 Pivot app: Preview of My Current Windows Phone 7 Pivot Work From SilverlightCream.com: A Chrome and Glass Theme - Part I Phil Middlemiss is starting a tutorial series on building a new theme for Silverlight, in this first one we define some gradients and color resources... good stuff Phil Intercepting INotifyPropertyChanged This is Robert Kozak's first post on this blog, but it's a good one about INotifyPropertyChanged and MVVM and has a solution in the post with lots of code and discussion. How do I Display Data of Complex Bound Criteria in Horizontal Lists in Silverlight? Kathleen Dollard's latest article in Visual Studio magazine is in answer to a question about displaying a list of complex bound criteria including data, child data, and photos, and displaying them horizontally one at a time. Very nice-looking result, and all the code. Windows Phone: Frame/Page navigation and transitions using the TransitioningContentControl Avi Pilosof discusses the built-in (boring) navigation on WP7, and then shows using the TransitionContentControl from the Toolkit to apply transitions to the navigation. EasyPainter: Cloud Turbulence and Particle Buzz Nokola returns with a couple more effects for EasyPainter: Cloud Turbulence and Particle Buzz ... check out the example screenshots, then go grab the code. Property change notifications for multithreaded Silverlight applications Jeff Wilcox is discussing the need for getting change notifications to always happen on the UI thread in multi-threaded apps... great diagrams to see what's going on. Tip: The default value of a DependencyProperty is shared by all instances of the class that registers it David Anson has a tip up about setting the default value of a DependencyProperty, and the consequence that may have depending upon the type. Building a “real” extension for Expression Blend Timmy Kokke's code is WPF, but the subject is near and dear to us all, Timmy has a real-world Expression Blend extension up... a search for controls in the Objects and Timelines pane ... and even if that doesn't interest you... it's the source to a Blend extension! XPath support in Silverlight 4 + XPathPad Tim Greenfield not only talks about XPath in SL4RC, but he has produced a tool, XPathPad, and provided the source... if you've used XPath, you either are a higher thinker than me(not a big stretch), or you need this :) Using a Service Locator to Work with MessageBoxes in an MVVM Application Josh Smith posted about a question that comes up a lot: showing a messagebox from a ViewModel object. This might not work for custom message boxes or unit testing. This post covers the Unit Testing aspect. 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

  • Silverlight Cream for January 03, 2011 -- #1021

    - by Dave Campbell
    In this all-Submittal Issue: Gill Cleeren(-2-), Brian Noyes, Brian Genisio, René Schulte, and Andy Schwam(-2-). Above the Fold: Silverlight: "The INavigationContentLoader interface in Silverlight 4" Gill Cleeren WP7: "Sending Windows Phone Screenshots in an Email" René Schulte WCF RIA Services: "WCF RIA Services Part 10 - Exposing Domain Services To Other Clients" Brian Noyes Shoutouts: Want to know what it takes to be an MVP? Check out René Schulte's recap of 2010: Goodbye 2010 - Hello 2011 ... awesome, René! Rui Marinho sent me this post... it's WPF, but wow... WPF and Kinect! Kinect & WPF From SilverlightCream.com: The INavigationContentLoader interface in Silverlight 4 Gill Cleeren has a couple posts up... this first is a break-out of the INavigationContentLoader... what all can be done with it, in addition to the flow of the page load process broken out. Working with the RaiseCanExecuteChanged in MVVM Light (Silverlight) Gill Cleeren' latest post is a discussion of the Silverlight ICommand interface and Laurent Bugnion's RaiseCanExecuteChanged in MVVM Light, with example code. WCF RIA Services Part 10 - Exposing Domain Services To Other Clients Brian Noyes has Part 10 in his WCF RIA Services Tutorial series up at SilverlightShow ... with info on, for example, exposint an OData, SOAP, or REST/JSON endpoint, or how to consume them. Cross-Training in Silverlight & Flex–MVVM vs Presentation Model Brian Genisio finished the year off with this post in his on-going Silverlight/Flex seris comparing MVVM vs Presentation Model .. lots of good MVVM/ViewModel tips and code in this post. Sending Windows Phone Screenshots in an Email René Schulte is the perfect guy to be doing this... how about emailing a screenshot directly from inside an app, for instance Laurent's taking a screenshot from inside an app... too cool, Rene! Windows Phone 7 Application Development Tips Andy Schwam has a post up with tips he learned while creating his first WP7 app... lots of good tips, Gestures, Camera, ISO... check it out, could save you some time and tears :) WP7 Tip: Using the CameraCaptureTask for Windows Phone 7 Andy Schwam's most recent post is WP7 dev as well, and has a bunch of tips and code for using the camera, such as capturing an image, resizing, saving... good stuff. 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

  • Silverlight Cream for March 10, 2010 - 2 -- #811

    - by Dave Campbell
    In this Issue: AfricanGeek, Phil Middlemiss, Damon Payne, David Anson, Jesse Liberty, Jeremy Likness, Jobi Joy(-2-), Fredrik Normén, Bobby Diaz, and Mike Taulty(-2-). Shoutouts: Shawn Wildermuth blogged that they posted My "What's New in Silverlight 3" Video from 0reDev Last Fall Shawn Wildermuth also has a post up for his loyal followers: Where to See Me At MIX10 Jonas Follesø has presentation materials up as well: MVVM presentation from NDC2009 on Vimeo Adam Kinney updated his Favorite Tool and Library Downloads for Silverlight From SilverlightCream.com: Styling Silverlight ListBox with Blend 3 In his latest Video Tutorial, AfricanGeek is animating the ListBox control by way of Expression Blend 3. Animating the Silverlight Opacity Mask Phil Middlemiss has written a Behavior that lets you turn a FrameworkElement into an opacity mask for it's parent container... check out his tutorial and grab the code. AddRange for ObservableCollection in Silverlight 3 Damon Payne has a post up discussing the problem with large amounts of data in an ObservableCollection, and how using AddRange is a performance booster. Easily rotate the axis labels of a Silverlight/WPF Toolkit chart David Anson blogged a solution to rotating the axis labels of a Silverlight and WPF chart. Persisting the Configuration (Updated) Jesse Liberty has a good discussion on the continuation of his HyperVideo Platform talking about what all he is needing from the database in the form of configuration information... including the relationships. Animations and View Models: IAnimationDelegate Check out Jeremy Likness' IAnimationDelegate that lets your ViewModel fire and respond to animations without having to know all about them. Button Style - Silverlight Jobi Joy converted a WPF control template into Silverlight... and you'll want to download the XAML he's got for this :) A Simple Accordion banner using ListBox Jobi Joy also has an Image Accordian created in Expression Blend... and it's a 'drop this XAML in your User Control' kinda thing... again, go grab the XAML :) WCF RIA Services Silverlight Business Application – Using ASP.NET SiteMap for Navigation Fredrik Normén has a code-laden post up on RIA Services and the ASP.NET SiteMap. He is using the Silverlight Business app template that comes with WCF RIA Services. A Simple, Selectable Silverlight TextBlock (sort of)... Bobby Diaz shares with us his solution for a Text control that can be copied from in the same manner 'normal' web controls can be. He also includes a link to another post on the same topic. Silverlight 4 Beta Networking. Part 11 - WCF and TCP Mike Taulty has another pair of video tutorials up in his Networking series. This one is on WCF over TCP Silverlight 4 Beta Networking. Part 12 - WCF and Polling HTTP Mike Taulty's 12th networking video tutorial is on WCF with HTTP polling duplex. 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    MIX10

    Read the article

  • Skinny controller in ASP.NET MVC 4

    - by thangchung
    Rails community are always inspire a lot of best ideas. I really love this community by the time. One of these is "Fat models and skinny controllers". I have spent a lot of time on ASP.NET MVC, and really I did some miss-takes, because I made the controller so fat. That make controller is really dirty and very hard to maintain in the future. It is violate seriously SRP principle and KISS as well. But how can we achieve that in ASP.NET MVC? That question is really clear after I read "Manning ASP.NET MVC 4 in Action". It is simple that we can separate it into ActionResult, and try to implementing logic and persistence data inside this. In last 2 years, I have read this from Jimmy Bogard blog, but in that time I never had a consideration about it. That's enough for talking now. I just published a sample on ASP.NET MVC 4, implemented on Visual Studio 2012 RC at here. I used EF framework at here for implementing persistence layer, and also use 2 free templates from internet to make the UI for this sample. In this sample, I try to implementing the simple magazine website that managing all articles, categories and news. It is not finished at all in this time, but no problems, because I just show you about how can we make the controller skinny. And I wanna hear more about your ideas. The first thing, I am abstract the base ActionResult class like this:    public abstract class MyActionResult : ActionResult, IEnsureNotNull     {         public abstract void EnsureAllInjectInstanceNotNull();     }     public abstract class ActionResultBase<TController> : MyActionResult where TController : Controller     {         protected readonly Expression<Func<TController, ActionResult>> ViewNameExpression;         protected readonly IExConfigurationManager ConfigurationManager;         protected ActionResultBase (Expression<Func<TController, ActionResult>> expr)             : this(DependencyResolver.Current.GetService<IExConfigurationManager>(), expr)         {         }         protected ActionResultBase(             IExConfigurationManager configurationManager,             Expression<Func<TController, ActionResult>> expr)         {             Guard.ArgumentNotNull(expr, "ViewNameExpression");             Guard.ArgumentNotNull(configurationManager, "ConfigurationManager");             ViewNameExpression = expr;             ConfigurationManager = configurationManager;         }         protected ViewResult GetViewResult<TViewModel>(TViewModel viewModel)         {             var m = (MethodCallExpression)ViewNameExpression.Body;             if (m.Method.ReturnType != typeof(ActionResult))             {                 throw new ArgumentException("ControllerAction method '" + m.Method.Name + "' does not return type ActionResult");             }             var result = new ViewResult             {                 ViewName = m.Method.Name             };             result.ViewData.Model = viewModel;             return result;         }         public override void ExecuteResult(ControllerContext context)         {             EnsureAllInjectInstanceNotNull();         }     } I also have an interface for validation all inject objects. This interface make sure all inject objects that I inject using Autofac container are not null. The implementation of this as below public interface IEnsureNotNull     {         void EnsureAllInjectInstanceNotNull();     } Afterwards, I am just simple implementing the HomePageViewModelActionResult class like this public class HomePageViewModelActionResult<TController> : ActionResultBase<TController> where TController : Controller     {         #region variables & ctors         private readonly ICategoryRepository _categoryRepository;         private readonly IItemRepository _itemRepository;         private readonly int _numOfPage;         public HomePageViewModelActionResult(Expression<Func<TController, ActionResult>> viewNameExpression)             : this(viewNameExpression,                    DependencyResolver.Current.GetService<ICategoryRepository>(),                    DependencyResolver.Current.GetService<IItemRepository>())         {         }         public HomePageViewModelActionResult(             Expression<Func<TController, ActionResult>> viewNameExpression,             ICategoryRepository categoryRepository,             IItemRepository itemRepository)             : base(viewNameExpression)         {             _categoryRepository = categoryRepository;             _itemRepository = itemRepository;             _numOfPage = ConfigurationManager.GetAppConfigBy("NumOfPage").ToInteger();         }         #endregion         #region implementation         public override void ExecuteResult(ControllerContext context)         {             base.ExecuteResult(context);             var cats = _categoryRepository.GetCategories();             var mainViewModel = new HomePageViewModel();             var headerViewModel = new HeaderViewModel();             var footerViewModel = new FooterViewModel();             var mainPageViewModel = new MainPageViewModel();             headerViewModel.SiteTitle = "Magazine Website";             if (cats != null && cats.Any())             {                 headerViewModel.Categories = cats.ToList();                 footerViewModel.Categories = cats.ToList();             }             mainPageViewModel.LeftColumn = BindingDataForMainPageLeftColumnViewModel();             mainPageViewModel.RightColumn = BindingDataForMainPageRightColumnViewModel();             mainViewModel.Header = headerViewModel;             mainViewModel.DashBoard = new DashboardViewModel();             mainViewModel.Footer = footerViewModel;             mainViewModel.MainPage = mainPageViewModel;             GetViewResult(mainViewModel).ExecuteResult(context);         }         public override void EnsureAllInjectInstanceNotNull()         {             Guard.ArgumentNotNull(_categoryRepository, "CategoryRepository");             Guard.ArgumentNotNull(_itemRepository, "ItemRepository");             Guard.ArgumentMustMoreThanZero(_numOfPage, "NumOfPage");         }         #endregion         #region private functions         private MainPageRightColumnViewModel BindingDataForMainPageRightColumnViewModel()         {             var mainPageRightCol = new MainPageRightColumnViewModel();             mainPageRightCol.LatestNews = _itemRepository.GetNewestItem(_numOfPage).ToList();             mainPageRightCol.MostViews = _itemRepository.GetMostViews(_numOfPage).ToList();             return mainPageRightCol;         }         private MainPageLeftColumnViewModel BindingDataForMainPageLeftColumnViewModel()         {             var mainPageLeftCol = new MainPageLeftColumnViewModel();             var items = _itemRepository.GetNewestItem(_numOfPage);             if (items != null && items.Any())             {                 var firstItem = items.First();                 if (firstItem == null)                     throw new NoNullAllowedException("First Item".ToNotNullErrorMessage());                 if (firstItem.ItemContent == null)                     throw new NoNullAllowedException("First ItemContent".ToNotNullErrorMessage());                 mainPageLeftCol.FirstItem = firstItem;                 if (items.Count() > 1)                 {                     mainPageLeftCol.RemainItems = items.Where(x => x.ItemContent != null && x.Id != mainPageLeftCol.FirstItem.Id).ToList();                 }             }             return mainPageLeftCol;         }         #endregion     }  Final step, I get into HomeController and add some line of codes like this [Authorize]     public class HomeController : BaseController     {         [AllowAnonymous]         public ActionResult Index()         {             return new HomePageViewModelActionResult<HomeController>(x=>x.Index());         }         [AllowAnonymous]         public ActionResult Details(int id)         {             return new DetailsViewModelActionResult<HomeController>(x => x.Details(id), id);         }         [AllowAnonymous]         public ActionResult Category(int id)         {             return new CategoryViewModelActionResult<HomeController>(x => x.Category(id), id);         }     } As you see, the code in controller is really skinny, and all the logic I move to the custom ActionResult class. Some people said, it just move the code out of controller and put it to another class, so it is still hard to maintain. Look like it just move the complicate codes from one place to another place. But if you have a look and think it in details, you have to find out if you have code for processing all logic that related to HttpContext or something like this. You can do it on Controller, and try to delegating another logic  (such as processing business requirement, persistence data,...) to custom ActionResult class. Tell me more your thinking, I am really willing to hear all of its from you guys. All source codes can be find out at here. Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://weblogs.asp.net//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

    Read the article

  • Silverlight Cream for January 14, 2011 -- #1027

    - by Dave Campbell
    In this Issue: Sigurd Snørteland, Yochay Kiriaty, WindowsPhoneGeek(-2-), Jesse Liberty(-2-), Kunal Chowdhury, Martin Krüger(-2-), Jonathan Cardy. Above the Fold: Silverlight: "Image Viewer using a GridSplitter control" Martin Krüger WP7: "Implementing WP7 ToggleImageControl from the ground up: Part1" WindowsPhoneGeek VS2010 Templates: "MVVM Project Templates for Visual Studio 2010" Jonathan Cardy From SilverlightCream.com: BabySmash7 - a WP7 children's game (source code included) Sigurd Snørteland not only brings Scott Hanselman's Baby Smash to WP7, but he's delivering the source to us as well as discussion of the app. Windows Push Notification Server Side Helper Library Yochay Kiriaty has a tutorial up on Push Notification... not explaining them, but a discussion of a WP7 Push Recipe that provides an easy way for sending all 3 kinds of push notification messages currently supported. Implementing WP7 ToggleImageControl from the ground up: Part1 WindowsPhoneGeek has a great 2-part series up on building a useful WP7 custom control -- a ToggleImage control... this part 1 is definition, deciding on Visual states, etc... buckle up... this is good stuff Implementing WP7 ToggleImageControl from the ground up: Part2 Part 2 in WindowsPhoneGeek's series is also up and where the real fun lives -- implementing the behavior of the control... and the source is available at the end of this post. The Full Stack #5 – Entity Framework Code First Jesse Liberty has episode 5 of the "Full Stack" series he and Jon Galloway are doing and are discussing Entity Framework Code First. Windows Phone From Scratch #18 – MVVM Light Toolkit Soup To Nuts 3 Jesse Liberty also has part 3 of his MVVMLight and WP7 post up and is digging into messaging in this one... for example view <--> ViewModel communication. Exploring Ribbon Control for Silverlight (Part - 1) Kunal Chowdhury has part 1 of a series up on using the Silverlight Ribbon Control from DevComponents... lots of information and a great intro to a great control. Image Viewer using a GridSplitter control Martin Krüger has a very nice picture viewer up as a demo and code available that simply uses the GridSplitter to implement tha aperture... check it out. How to: Gentle animation of a magnify effect Martin Krüger's latest is a take-off on a prior post he links to called 'just for fun' in which he smoothly animates a magnify effect... just very cool animation... explanation and source. MVVM Project Templates for Visual Studio 2010 Jonathan Cardy has a couple resources you probably wanna grab... two MVVM project templates for VS2010... one WPF and one Silverlight 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 | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >