Search Results

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

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

  • Update database using restful ASP.NET MVC 1.0

    - by Mike
    We are building an MVC 1.0 application right now and using Linq - SQL for our DAL. Following the restful approach we have multiple action events depending on if you are updating or loading or what not. The two that I'm concerned with at this point are the edit and update action methods. Here is the signatures. public ActionResult Update(int customerId, int Id, AggregateModel viewModel) public ActionResult Edit(int customerId, int Id, AggregateModel viewModel) So the idea is that in the Edit method we load up our viewModel and pass it to the view. The user makes changes to the model and then posts back to the Update method. The first thing I could think of to do would be to get the viewModel from the database again, copy the changes in one by one from the posted back model and then submit it back. This would work but does seem clunky to me. What is the best way to insert those changes into the database at this point?

    Read the article

  • What is the architectural name for the set of data that enables UI choices?

    - by Richard Collette
    I have separate service methods that fetch business object data and the data for UI selection input such as radio buttons, check-boxes, combo-boxes, etc. I want to name my service methods that fetch the selection data appropriately. I am assuming that Model and ViewModel would not be part of the name because the selection data is but a portion of the Model or ViewModel. What might this set of data be named such that I can name my service method?

    Read the article

  • Announcing ASP.NET MVC 3 (Release Candidate 2)

    - by ScottGu
    Earlier today the ASP.NET team shipped the final release candidate (RC2) for ASP.NET MVC 3.  You can download and install it here. Almost there… Today’s RC2 release is the near-final release of ASP.NET MVC 3, and is a true “release candidate” in that we are hoping to not make any more code changes with it.  We are publishing it today so that people can do final testing with it, let us know if they find any last minute “showstoppers”, and start updating their apps to use it.  We will officially ship the final ASP.NET MVC 3 “RTM” build in January. Works with both VS 2010 and VS 2010 SP1 Beta Today’s ASP.NET MVC 3 RC2 release works with both the shipping version of Visual Studio 2010 / Visual Web Developer 2010 Express, as well as the newly released VS 2010 SP1 Beta.  This means that you do not need to install VS 2010 SP1 (or the SP1 beta) in order to use ASP.NET MVC 3.  It works just fine with the shipping Visual Studio 2010.  I’ll do a blog post next week, though, about some of the nice additional feature goodies that come with VS 2010 SP1 (including IIS Express and SQL CE support within VS) which make the dev experience for both ASP.NET Web Forms and ASP.NET MVC even better. Bugs and Perf Fixes Today’s ASP.NET MVC 3 RC2 build contains many bug fixes and performance optimizations.  Our latest performance tests indicate that ASP.NET MVC 3 is now faster than ASP.NET MVC 2, and that existing ASP.NET MVC applications will experience a slight performance increase when updated to run using ASP.NET MVC 3. Final Tweaks and Fit-N-Finish In addition to bug fixes and performance optimizations, today’s RC2 build contains a number of last-minute feature tweaks and “fit-n-finish” changes for the new ASP.NET MVC 3 features.  The feedback and suggestions we’ve received during the public previews has been invaluable in guiding these final tweaks, and we really appreciate people’s support in sending this feedback our way.  Below is a short-list of some of the feature changes/tweaks made between last month’s ASP.NET MVC 3 RC release and today’s ASP.NET MVC 3 RC2 release: jQuery updates and addition of jQuery UI The default ASP.NET MVC 3 project templates have been updated to include jQuery 1.4.4 and jQuery Validation 1.7.  We are also excited to announce today that we are including jQuery UI within our default ASP.NET project templates going forward.  jQuery UI provides a powerful set of additional UI widgets and capabilities.  It will be added by default to your project’s \scripts folder when you create new ASP.NET MVC 3 projects. Improved View Scaffolding The T4 templates used for scaffolding views with the Add-View dialog now generates views that use Html.EditorFor instead of helpers such as Html.TextBoxFor. This change enables you to optionally annotate models with metadata (using data annotation attributes) to better customize the output of your UI at runtime. The Add View scaffolding also supports improved detection and usage of primary key information on models (including support for naming conventions like ID, ProductID, etc).  For example: the Add View dialog box uses this information to ensure that the primary key value is not scaffold as an editable form field, and that links between views are auto-generated correctly with primary key information. The default Edit and Create templates also now include references to the jQuery scripts needed for client validation.  Scaffold form views now support client-side validation by default (no extra steps required).  Client-side validation with ASP.NET MVC 3 is also done using an unobtrusive javascript approach – making pages fast and clean. [ControllerSessionState] –> [SessionState] ASP.NET MVC 3 adds support for session-less controllers.  With the initial RC you used a [ControllerSessionState] attribute to specify this.  We shortened this in RC2 to just be [SessionState]: Note that in addition to turning off session state, you can also set it to be read-only (which is useful for webfarm scenarios where you are reading but not updating session state on a particular request). [SkipRequestValidation] –> [AllowHtml] ASP.NET MVC includes built-in support to protect against HTML and Cross-Site Script Injection Attacks, and will throw an error by default if someone tries to post HTML content as input.  Developers need to explicitly indicate that this is allowed (and that they’ve hopefully built their app to securely support it) in order to enable it. With ASP.NET MVC 3, we are also now supporting a new attribute that you can apply to properties of models/viewmodels to indicate that HTML input is enabled, which enables much more granular protection in a DRY way.  In last month’s RC release this attribute was named [SkipRequestValidation].  With RC2 we renamed it to [AllowHtml] to make it more intuitive: Setting the above [AllowHtml] attribute on a model/viewmodel will cause ASP.NET MVC 3 to turn off HTML injection protection when model binding just that property. Html.Raw() helper method The new Razor view engine introduced with ASP.NET MVC 3 automatically HTML encodes output by default.  This helps provide an additional level of protection against HTML and Script injection attacks. With RC2 we are adding a Html.Raw() helper method that you can use to explicitly indicate that you do not want to HTML encode your output, and instead want to render the content “as-is”: ViewModel/View –> ViewBag ASP.NET MVC has (since V1) supported a ViewData[] dictionary within Controllers and Views that enables developers to pass information from a Controller to a View in a late-bound way.  This approach can be used instead of, or in combination with, a strongly-typed model class.  The below code demonstrates a common use case – where a strongly typed Product model is passed to the view in addition to two late-bound variables via the ViewData[] dictionary: With ASP.NET MVC 3 we are introducing a new API that takes advantage of the dynamic type support within .NET 4 to set/retrieve these values.  It allows you to use standard “dot” notation to specify any number of additional variables to be passed, and does not require that you create a strongly-typed class to do so.  With earlier previews of ASP.NET MVC 3 we exposed this API using a dynamic property called “ViewModel” on the Controller base class, and with a dynamic property called “View” within view templates.  A lot of people found the fact that there were two different names confusing, and several also said that using the name ViewModel was confusing in this context – since often you create strongly-typed ViewModel classes in ASP.NET MVC, and they do not use this API.  With RC2 we are exposing a dynamic property that has the same name – ViewBag – within both Controllers and Views.  It is a dynamic collection that allows you to pass additional bits of data from your controller to your view template to help generate a response.  Below is an example of how we could use it to pass a time-stamp message as well as a list of all categories to our view template: Below is an example of how our view template (which is strongly-typed to expect a Product class as its model) can use the two extra bits of information we passed in our ViewBag to generate the response.  In particular, notice how we are using the list of categories passed in the dynamic ViewBag collection to generate a dropdownlist of friendly category names to help set the CategoryID property of our Product object.  The above Controller/View combination will then generate an HTML response like below.    Output Caching Improvements ASP.NET MVC 3’s output caching system no longer requires you to specify a VaryByParam property when declaring an [OutputCache] attribute on a Controller action method.  MVC3 now automatically varies the output cached entries when you have explicit parameters on your action method – allowing you to cleanly enable output caching on actions using code like below: In addition to supporting full page output caching, ASP.NET MVC 3 also supports partial-page caching – which allows you to cache a region of output and re-use it across multiple requests or controllers.  The [OutputCache] behavior for partial-page caching was updated with RC2 so that sub-content cached entries are varied based on input parameters as opposed to the URL structure of the top-level request – which makes caching scenarios both easier and more powerful than the behavior in the previous RC. @model declaration does not add whitespace In earlier previews, the strongly-typed @model declaration at the top of a Razor view added a blank line to the rendered HTML output. This has been fixed so that the declaration does not introduce whitespace. Changed "Html.ValidationMessage" Method to Display the First Useful Error Message The behavior of the Html.ValidationMessage() helper was updated to show the first useful error message instead of simply displaying the first error. During model binding, the ModelState dictionary can be populated from multiple sources with error messages about the property, including from the model itself (if it implements IValidatableObject), from validation attributes applied to the property, and from exceptions thrown while the property is being accessed. When the Html.ValidationMessage() method displays a validation message, it now skips model-state entries that include an exception, because these are generally not intended for the end user. Instead, the method looks for the first validation message that is not associated with an exception and displays that message. If no such message is found, it defaults to a generic error message that is associated with the first exception. RemoteAttribute “Fields” -> “AdditionalFields” ASP.NET MVC 3 includes built-in remote validation support with its validation infrastructure.  This means that the client-side validation script library used by ASP.NET MVC 3 can automatically call back to controllers you expose on the server to determine whether an input element is indeed valid as the user is editing the form (allowing you to provide real-time validation updates). You can accomplish this by decorating a model/viewmodel property with a [Remote] attribute that specifies the controller/action that should be invoked to remotely validate it.  With the RC this attribute had a “Fields” property that could be used to specify additional input elements that should be sent from the client to the server to help with the validation logic.  To improve the clarity of what this property does we have renamed it to “AdditionalFields” with today’s RC2 release. ViewResult.Model and ViewResult.ViewBag Properties The ViewResult class now exposes both a “Model” and “ViewBag” property off of it.  This makes it easier to unit test Controllers that return views, and avoids you having to access the Model via the ViewResult.ViewData.Model property. Installation Notes You can download and install the ASP.NET MVC 3 RC2 build here.  It can be installed on top of the previous ASP.NET MVC 3 RC release (it should just replace the bits as part of its setup). The one component that will not be updated by the above setup (if you already have it installed) is the NuGet Package Manager.  If you already have NuGet installed, please go to the Visual Studio Extensions Manager (via the Tools –> Extensions menu option) and click on the “Updates” tab.  You should see NuGet listed there – please click the “Update” button next to it to have VS update the extension to today’s release. If you do not have NuGet installed (and did not install the ASP.NET MVC RC build), then NuGet will be installed as part of your ASP.NET MVC 3 setup, and you do not need to take any additional steps to make it work. Summary We are really close to the final ASP.NET MVC 3 release, and will deliver the final “RTM” build of it next month.  It has been only a little over 7 months since ASP.NET MVC 2 shipped, and I’m pretty amazed by the huge number of new features, improvements, and refinements that the team has been able to add with this release (Razor, Unobtrusive JavaScript, NuGet, Dependency Injection, Output Caching, and a lot, lot more).  I’ll be doing a number of blog posts over the next few weeks talking about many of them in more depth. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • Making Modular, Reusable and Loosely Coupled MVC Components

    - by Dusan
    I am building MVC3 application and need some general guidelines on how to manage complex client side interaction between my components. Here is my definition of one component in general way: Component which has it's own controller, model and view. All of the component's logic is placed inside these three parts and component is sort of "standalone", it contains it's own form, data needed for interaction, updates itself with Ajax and so on. Beside this internal logic and behavior of the component, it needs to be able to "Talk" to the outside world. By this I mean it should provide data and events (sort of) so when this component gets embedded in pages can notify other components which then can update based on the current state and data. I have an idea to use client ViewModel (in java-script) which would hookup all relevant components on page and control interaction between them. This would make components reusable, modular - independent of the context in which they are used. How would you do this, I am a bit stuck as I do not know if this is a good approach and there is a technical possibility to achieve this using java-script/jquery. The confusing part is about update via Ajax, how to ensure that component is properly linked to ViewModel when component is Ajax updated (or even worse removed or dynamically added). Also, how should this ViewModel be constructed and which technicalities to use here and in components to work as synergy??? On the web, I have found the various examples of the similar approach, but they are oversimplified (even for dummies) or over specific and do not provide valuable resource or general solution for this kind of implementation. If you have some serious examples it would be, also, very helpful. Note: My aim is to make interactions between many components on the same page simpler and more robust and elegant.

    Read the article

  • asp.net mvc2 - controller for master page and code organization

    - by ile
    I've just finished my first ASP.NET MVC (2) CMS. Next step is to build website that will show data from CMS's database. This is website design: #1 (Red box) - displays article categories. ViewModel: public class CategoriesDisplay { public CategoriesDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } } #2 (Brown box) - displays last x articles; skips those from green box #3. Viewmodel: public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public string URLArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } #3 (green box) - Displays last x articles. Uses the same ViewModel as brown box #2 #4 (blue box) - Displays list of upcoming events. Uses dataContext.Model.Event as ViewModel Boxes #1, #2 and #4 will repeat all over the site and they are part of Master Page. So, my question is: what is the best way to transfer this data from Model to Controller and finally to View pages? Should I make a controller for master page and ViewModel class that will wrap all this classes together OR Should I create partial Views for every of these boxes and make each of them inherit appropriate class (if it is even possible that it works this way?) OR Should I put this repeated code in all controllers and all additional data transfer via ViewData, which would be probably the worse way :) OR There is maybe a better and more simple way but I don't know/see it? Thanks in advance, Ile EDIT: If your answer is #1, then please explain how to make a controller for master page! EDIT 2: In this tutorial is described how to pass data to master page using abstract class: http://www.asp.net/LEARN/mvc/tutorial-13-cs.aspx In "Listing 5 – Controllers\MoviesController.cs", data is retrieved directly from database using LINQ, not from repository. So, I wonder if this is just in this tutorial, or there is some trick here and repository can't/shouldn't be used?

    Read the article

  • Keeping the DI-container usage in the composition root in Silverlight and MVVM

    - by adrian hara
    It's not quite clear to me how I can design so I keep the reference to the DI-container in the composition root for a Silverlight + MVVM application. I have the following simple usage scenario: there's a main view (perhaps a list of items) and an action to open an edit view for one single item. So the main view has to create and show the edit view when the user takes the action (e.g. clicks some button). For this I have the following code: public interface IView { IViewModel ViewModel {get; set;} } Then, for each view that I need to be able to create I have an abstract factory, like so public interface ISomeViewFactory { IView CreateView(); } This factory is then declared a dependency of the "parent" view model, like so: public class SomeParentViewModel { public SomeParentViewModel(ISomeViewFactory viewFactory) { // store it } private void OnSomeUserAction() { IView view = viewFactory.CreateView(); dialogService.ShowDialog(view); } } So all is well until here, no DI-container in sight :). Now comes the implementation of ISomeViewFactory: public class SomeViewFactory : ISomeViewFactory { public IView CreateView() { IView view = new SomeView(); view.ViewModel = ???? } } The "????" part is my problem, because the view model for the view needs to be resolved from the DI-container so it gets its dependencies injected. What I don't know is how I can do this without having a dependency to the DI-container anywhere except the composition root. One possible solution would be to have either a dependency on the view model that gets injected into the factory, like so: public class SomeViewFactory : ISomeViewFactory { public SomeViewFactory(ISomeViewModel viewModel) { // store it } public IView CreateView() { IView view = new SomeView(); view.ViewModel = viewModel; } } While this works, it has the problem that since the whole object graph is wired up "statically" (i.e. the "parent" view model will get an instance of SomeViewFactory, which will get an instance of SomeViewModel, and these will live as long as the "parent" view model lives), the injected view model implementation is stateful and if the user opens the child view twice, the second time the view model will be the same instance and have the state from before. I guess I could work around this with an "Initialize" method or something similar, but it doesn't smell quite right. Another solution might be to wrap the DI-container and have the factories depend on the wrapper, but it'd still be a DI-container "in disguise" there :) Any thoughts on this are greatly appreciated. Also, please forgive any mistakes or rule-breaking, since this is my first post on stackoverflow :) Thanks! ps: my current solution is that the factories know about the DI-container, and it's only them and the composition root that have this dependency.

    Read the article

  • Why does my ko computed observable not update bound UI elements when its value changes?

    - by Allen
    I'm trying to wrap a cookie in a computed observable (which I'll later turn into a protectedObservable) and I'm having some problems with the computed observable. I was under the opinion that changes to the computed observable would be broadcast to any UI elements that have been bound to it. I've created the following fiddle JavaScript: var viewModel = {}; // simulating a cookie store, this part isnt as important var cookie = function () { // simulating a value stored in cookies var privateZipcode = "12345"; return { 'write' : function (val) { privateZipcode = val; }, 'read': function () { return privateZipcode; } } }(); viewModel.zipcode = ko.computed({ read: function () { return cookie.read(); }, write: function (value) { cookie.write(value); }, owner: viewModel }); ko.applyBindings(viewModel);? HTML: zipcode: <input type='text' data-bind="value: zipcode"> <br /> zipcode: <span data-bind="text: zipcode"></span>? I'm not using an observable to store privateZipcode since that's really just going to be in a cookie. I'm hoping that the ko.computed will provide the notifications and binding functionality that I need, though most of the examples I've seen with ko.computed end up using a ko.observable underneath the covers. Shouldn't the act of writing the value to my computed observable signal the UI elements that are bound to its value? Shouldn't these just update? Workaround I've got a simple workaround where I just use a ko.observable along side of my cookie store and using that will trigger the required updates to my DOM elements but this seems completely unnecessary, unless ko.computed lacks the signaling / dependency type functionality that ko.observable has. My workaround fiddle, you'll notice that the only thing that changes is that I added a seperateObservable that isn't used as a store, its only purpose is to signal to the UI that the underlying data has changed. // simulating a cookie store, this part isnt as important var cookie = function () { // simulating a value stored in cookies var privateZipcode = "12345"; // extra observable that isnt really used as a store, just to trigger updates to the UI var seperateObservable = ko.observable(privateZipcode); return { 'write' : function (val) { privateZipcode = val; seperateObservable(val); }, 'read': function () { seperateObservable(); return privateZipcode; } } }(); This makes sense and works as I'd expect because viewModel.zipcode depends on seperateObservable and updates to that should (and does) signal the UI to update. What I don't understand, is why doesn't a call to the write function on my ko.computed signal the UI to update, since that element is bound to that ko.computed? I suspected that I might have to use something in knockout to manually signal that my ko.computed has been updated, and I'm fine with that, that makes sense. I just haven't been able to find a way to accomplish that.

    Read the article

  • C# mvc 3 using selectlist with selected value in view

    - by Rob
    I'm working on a MVC3 web application. I want a list of categories shown when editing a blo from whe applications managements system. In my viewmodel i've got the following property defined for a list of selectlistitems for categories. /// <summary> /// The List of categories /// </summary> [Display(Name = "Categorie")] public IEnumerable<SelectListItem> Categories { get; set; } The next step, my controller contains the following edit action where the list of selectlistitems is filled from the database. public ActionResult Edit(Guid id) { var blogToEdit = _blogService.First(x => x.Id.Equals(id)); var listOfCategories = _categorieService.GetAll(); var selectList = listOfCategories.Select(x =>new SelectListItem{Text = x.Name, Value = x.Id.ToString(), Selected = x.Id.Equals(blogToEdit.Category.Id)}).ToList(); selectList.Insert(0, new SelectListItem{Text = Messages.SelectAnItem, Value = Messages.SelectAnItem}); var viewModel = new BlogModel { BlogId = blogToEdit.Id, Active = blogToEdit.Actief, Content = blogToEdit.Text, Title = blogToEdit.Titel, Categories = selectList //at this point i see the expected item being selected //Categories = new IEnumerable<SelectListItem>(listOfCategories, "Id", "Naam", blogToEdit.CategorieId) }; return View(viewModel); } When i set a breakpoint just before the view is being returned, i see that the selectlist is filled as i expected. So at this point everything seems to be okay. The viewmodel is filled entirely correct. Then in my view (i'm using Razor) i've got the following two rules which are supposed to render the selectlist for me. @Html.LabelFor(m => m.Categories) @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId) @Html.ValidationMessageFor(m => m.Categories) When I run the code and open the view to edit my blog, I can see all the correct data. Also the selectlist is rendered correctly, but the item i want to be selected lost it's selection. How can this be? Until the point the viewmodel is being returned with the view everything is okay. But when i view the webpage in the browser, the selectlist is there only with out the correct selection. What am I missing here? Or doing wrong?

    Read the article

  • Handle exceptions with WPF and MVVM

    - by Jon Cahill
    I am attempting to build an application using WPF and the MVVM pattern. I have my Views being populated from my ViewModel purely through databinding. I want to have a central place to handle all exceptions which occur in my application so I can notify the user and log the error appropriately. I know about Dispatcher.UnhandledException but this does not do the job as exception that occur during databinding are logged to the output windows. Because my View is databound to my ViewModel the entire application is pretty much controlled via databinding so I have no way to log my errors. Is there a way to generically handle the exceptions raised during databinding, without having to put try blocks around all my ViewModel public's? Example View: <Window x:Class="Test.TestView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TestView" Height="600" Width="800" WindowStartupLocation="CenterScreen"> <Window.Resources> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> </Window.Resources> <StackPanel VerticalAlignment="Center"> <Label Visibility="{Binding DisplayLabel, Converter={StaticResource BooleanToVisibilityConverter}}">My Label</Label> </StackPanel> </Window> The ViewModel: public class TestViewModel { public bool DisplayLabel { get { throw new NotImplementedException(); } } } It is an internal application so I do not want to use Wer as I have seen previously recommended.

    Read the article

  • MVVM Binding in Silverlight3 ItemsControl to get the parent controls DataContext

    - by BigTundra
    I have the following ItemsControl in Silverlight 3. <ItemsControl ItemsSource="{Binding ValueCollectionList}"> <ItemsControl.ItemTemplate> <DataTemplate> <Button x:Name="MyBtn" Height="40" Content="{Binding Name}" Tag="{Binding Value}" cmd:ButtonBaseExtensions.Command="{Binding ElementName=LayoutRoot, Path=ButtonCommand}" cmd:ButtonBaseExtensions.CommandParameter="{Binding ElementName=MyBtn, Path=Tag}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> The Problem is that I have the ItemsControl bound to the Collection in my ViewModel, but I need the button to trigger a command on the ViewModel which is of course not Available in the DataContext of the button since it only contains the collection. I can make the command fire by setting my ViewModel as a Resource and then binding to it as a StaticResource, but I want to know why the element to element binding won't work in this scenario. I would prefer not to use the StaticResource binding because that requires the default constructor on the ViewModel and so I can't inject my data easily.

    Read the article

  • How can I mock this asynchronous method?

    - by Charlie
    I have a class that roughly looks like this: public class ViewModel { public ViewModel(IWebService service) { this.WebService = service; } private IWebService WebService{get;set;} private IEnumerable<SomeData> MyData{get;set;} private void GetReferenceData() { this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null); } private void GetReferenceDataOnComplete(IAsyncResult result) { this.MyData = this.WebService.EndGetStaticReferenceData(result); } . . . } I want to mock my IWebService interface so that when BeginGetStaticReferenceData is called it is able to call the callback method. I'm using Moq and I can't work out how to do this. My unit test set up code looks something like: //Arrange var service = new Mock<IWebService>(); service.Setup(x => x.BeginGetStaticReferenceData(/*.......don't know.....*/)); service.Setup(x => x.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())).Returns(new List<SomeData>{new SomeData{Name="blah"}}); var viewModel = new ViewModel(service.Object); . .

    Read the article

  • BindAttribute, Exclude nested properties for complex types

    - by David Board
    I have a 'Stream' model: public class Stream { public int ID { get; set; } [Required] [StringLength(50, ErrorMessage = "Stream name cannot be longer than 50 characters.")] public string Name { get; set; } [Required] [DataType(DataType.Url)] public string URL { get; set; } [Required] [Display(Name="Service")] public int ServiceID { get; set; } public virtual Service Service { get; set; } public virtual ICollection<Event> Events { get; set; } public virtual ICollection<Monitor> Monitors { get; set; } public virtual ICollection<AlertRule> AlertRules { get; set; } } For the 'create' view for this model, I have made a view model to pass some additional information to the view: public class StreamCreateVM { public Stream Stream { get; set; } public SelectList ServicesList { get; set; } public int SelectedService { get; set; } } Here is my create post action: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")] StreamCreateVM viewModel) { if (ModelState.IsValid) { db.Streams.Add(viewModel.Stream); db.SaveChanges(); return RedirectToAction("Index", "Service", new { id = viewModel.Stream.ServiceID }); } return View(viewModel); } Now, this all works, apart from the [Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")] bit. I can't seem to Include or Exclude properties within a nested object.

    Read the article

  • WPF XAML references not resolved via myAssembly.GetReferencedAssemblies()

    - by WPF-it
    I have a WPF container application (with ContentControl host) and a containee application (UserControl). Both are oblivious of each other. Only one XML config file holds the string dllpath of the containee's DLL and full namespace name of the ViewModelClass inside the containee. A generic code in container resolves containee's assembly (Assembly.LoadFrom(dllpath)) and creates the viewmodel's instance using Activator.CreateInstance(vmType). when this viewmodel is hosted inside the ContentControl of the container, and relevant vierwmodel specific ResourceDictionary is added to ContentControl.Resources.MergedDictionaries of the content control of container, so the view loads fine. Now my containee has to host the WPF DataGrid using assembly reference of WPFToolkit.dll from my local C:\Lib folder. The Copy Local reference to the WPFToolkit.dll is added to the .csproj file of the containee's project and its only referred in the UserControl.XAML using its XAML namepsace. This way my bin\debug folder in my containee application, gets the WPFToolkit.dll copied. XAML: xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" <Controls:DataGrid ItemsSource="{Binding AssetList}" ... /> Issue: The moment the ViewModel (i.e. the containee's usercontrol) tries to load itself I get this error. "Cannot find type 'Microsoft.Windows.Controls.DataGrid'. The assembly used when compiling might be different than that used when loading and the type is missing." Hence I tried to load the referenced assemblies of the containee's assembly (myAssembly.GetReferencedAssemblies()) before the viewmodel is hosted. But WPFToolkit isnt there in that list of assemblies! Strange thing is I have another dll referred called Logger.dll in the containee codebase but this one is implemented using C# code behind. So I get its reference correctly resolved in myAssembly.GetReferencedAssemblies(). So does that mean BAML references of assemblies are never resolvable by GetReferencedAssemblies?

    Read the article

  • Render different view depending on the type of the data

    - by Miau
    Hi there So lets suppose we have an action in a controller that looks a bit like this: public ViewResult SomeAction(int id) { var data = _someService.GetData(id); ... //create new view model based on the data here return View(viewModel); } What I m trying to figure out is the best way to render a diferent view based on the type fo the data. the "_someService.GetData method returns an data that knows its out type (ie not only you can do typeof(data) but also you can do data.DataType and you ll get an enum value so I could achieve what I m trying to do doing something kinda like this public ViewResult SomeAction(int id) { var data = _someService.GetData(id); //I m mapping fields to the viewModel here var viewModel = GetViewModel(data); swtich(data.DataType) case DataType.TypeOne: return View("TypeOne", viewModel); break; ... } But this does not seem to be the nicest way, (I dont event know if it would work) Is this the way to go? Should I use some sort of RenderPartial Aproach? after all , waht will change in the view is mostly the order of the data (ie the rest of the view would be quite similar) Cheers

    Read the article

  • Bind an Incode DataTemplate in WPF

    - by Mike Bynum
    I have a WPF Application which is using MVVM. I know that there ways of doing this in XAML but I am working on a plugin architecture and came up with a solution where a plugin exposes it's viewmodel to my plugin host's viewmodel and it's datatemplate. I want to leave the lifetime management of the plugin view up to WPF. I have tried having the plugins expose a UserControl but ran into issues when WPF decided to dispose of my UserControl so I would not reattach it without weird hacky work arounds. I am having issues getting some sort of binding working to where i can bind a control to the data and it's template to my data template. I have a ViewModel which looks something like: public class MyViewModel { public DataTemplate SelectedTemplate{ get; set;} public object SelectedViewModel {get; set;} } The selected template and viewmodel are determined somewhere else in the code but are irrelevant to my question. My question is how i can bind to a DataTemplate so that I know how to display the data shown in the SelectedViewModel. The DataTemplate is a DataTemplate created incode which respresents: <DataTemplate DataType="{x:Type vm:MyViewModel}"> <v:MyUserControl /> </DataTemplate> I have tried: <UserControl Template="{Binding Path=SelectedTemplate}" Content="{Binding Path=SelectedViewModel"} /> But UserControl expects a control template and not a data template.

    Read the article

  • WPF Treeview contextmenu IsChecked binding MVVM

    - by BrettRobi
    I've got a TreeView to which I associate a ContextMenu. That contextmenu has an item whose IsChecked property I want to bind to my ViewModel. Since I am using a tree each treeitem is bound to a subproperty of my ViewModel. In the VS2010 output window I am seeing this databinding error: BindingExpression path error: 'IsAutoStart' property not found on 'object' ''HostMgmtViewModel' (HashCode=12565727)'. BindingExpression:Path=IsAutoStart; DataItem='HostMgmtViewModel' This clearly shows it is trying to bind to my ViewModel and not to the treeitem's associated data. How do I bind to the correct object? Remember my contextmenu is associated with the whole TreeView not to the specific treeitem.

    Read the article

  • Good examples of MVVM Template

    - by jwarzech
    I am currently working with the Microsoft MVVM template and find the lack of detailed examples frustrating. The included ContactBook example shows very little Command handling and the only other example I've found is from an MSDN Magazine article where the concepts are similar but uses a slightly different approach and still lack in any complexity. Are there any decent MVVM examples that at least show basic CRUD operations and dialog/content switching? Everyone's suggestions were really useful and I will start compiling a list of good resources Frameworks/Templates WPF Model-View-ViewModel Toolkit MVVM Light Toolkit Prism Caliburn Cinch Useful Articles Data Validation in .NET 3.5 Using a ViewModel to Provide Meaningful Validation Error Messages Action based ViewModel and Model validation Dialogs Command Bindings in MVVM More than just MVC for WPF MVVM + Mediator Example Application Additional Libraries WPF Disciples' improved Mediator Pattern implementation(I highly recommend this for applications that have more complex navigation)

    Read the article

  • Big smart ViewModels, dumb Views, and any model, the best MVVM approach?

    - by Edward Tanguay
    The following code is a refactoring of my previous MVVM approach (Fat Models, skinny ViewModels and dumb Views, the best MVVM approach?) in which I moved the logic and INotifyPropertyChanged implementation from the model back up into the ViewModel. This makes more sense, since as was pointed out, you often you have to use models that you either can't change or don't want to change and so your MVVM approach should be able to work with any model class as it happens to exist. This example still allows you to view the live data from your model in design mode in Visual Studio and Expression Blend which I think is significant since you could have a mock data store that the designer connects to which has e.g. the smallest and largest strings that the UI can possibly encounter so that he can adjust the design based on those extremes. Questions: I'm a bit surprised that I even have to "put a timer" in my ViewModel since it seems like that is a function of INotifyPropertyChanged, it seems redundant, but it was the only way I could get the XAML UI to constantly (once per second) reflect the state of my model. So it would be interesting to hear anyone who may have taken this approach if you encountered any disadvantages down the road, e.g. with threading or performance. The following code will work if you just copy the XAML and code behind into a new WPF project. XAML: <Window x:Class="TestMvvm73892.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestMvvm73892" Title="Window1" Height="300" Width="300"> <Window.Resources> <ObjectDataProvider x:Key="DataSourceCustomer" ObjectType="{x:Type local:CustomerViewModel}" MethodName="GetCustomerViewModel"/> </Window.Resources> <DockPanel DataContext="{StaticResource DataSourceCustomer}"> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <TextBlock Text="{Binding Path=FirstName}"/> <TextBlock Text=" "/> <TextBlock Text="{Binding Path=LastName}"/> </StackPanel> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <TextBlock Text="{Binding Path=TimeOfMostRecentActivity}"/> </StackPanel> </DockPanel> </Window> Code Behind: using System; using System.Windows; using System.ComponentModel; using System.Threading; namespace TestMvvm73892 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } } //view model public class CustomerViewModel : INotifyPropertyChanged { private string _firstName; private string _lastName; private DateTime _timeOfMostRecentActivity; private Timer _timer; public string FirstName { get { return _firstName; } set { _firstName = value; this.RaisePropertyChanged("FirstName"); } } public string LastName { get { return _lastName; } set { _lastName = value; this.RaisePropertyChanged("LastName"); } } public DateTime TimeOfMostRecentActivity { get { return _timeOfMostRecentActivity; } set { _timeOfMostRecentActivity = value; this.RaisePropertyChanged("TimeOfMostRecentActivity"); } } public CustomerViewModel() { _timer = new Timer(CheckForChangesInModel, null, 0, 1000); } private void CheckForChangesInModel(object state) { Customer currentCustomer = CustomerViewModel.GetCurrentCustomer(); MapFieldsFromModeltoViewModel(currentCustomer, this); } public static CustomerViewModel GetCustomerViewModel() { CustomerViewModel customerViewModel = new CustomerViewModel(); Customer currentCustomer = CustomerViewModel.GetCurrentCustomer(); MapFieldsFromModeltoViewModel(currentCustomer, customerViewModel); return customerViewModel; } public static void MapFieldsFromModeltoViewModel(Customer model, CustomerViewModel viewModel) { viewModel.FirstName = model.FirstName; viewModel.LastName = model.LastName; viewModel.TimeOfMostRecentActivity = model.TimeOfMostRecentActivity; } public static Customer GetCurrentCustomer() { return Customer.GetCurrentCustomer(); } //INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } //model public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime TimeOfMostRecentActivity { get; set; } public static Customer GetCurrentCustomer() { return new Customer { FirstName = "Jim", LastName = "Smith", TimeOfMostRecentActivity = DateTime.Now }; } } }

    Read the article

  • What makes MVVM uniquely suited to WPF?

    - by Reed Copsey
    The Model-View-ViewModel is very popular with WPF and Silverlight. I've been using this for my most recent projects, and am a very large fan. I understand that it's a refinement of MVP. However, I am wondering exactly what unique characteristics of WPF (and Silverlight) allow MVVM to work, and prevent (or at least make difficult) this pattern from working using other frameworks or technologies. I know MVVM has a strong dependency on the powerful data binding technology within WPF. This is the one feature which many articles and blogs seem to mention as being the key to WPF providing the means of the strong separation of View from ViewModel. However, data binding exists in many forms in other UI frameworks. There are even projects like Truss that provide WPF-style databinding to POCO in .NET. What features, other than data binding, make WPF and Silverlight uniquely suited to Model-View-ViewModel?

    Read the article

  • WPF Statusbar Updates - help, I seem to be going round in circles

    - by David Ward
    I seem to be going round in circles. I have a WPF application that has a main ribbon window with a status bar. When you navigate to a "view" a user control is displayed as the content of the main window. The view has a ViewModel which handles retrieving data from the database and the View's datacontext is set to the ViewModel. What I want is to have the lengthy operation (data retrieval) run on a background thread and whilst it is running the status in the main window to report appropriately. When the background task is complete, the status should revert back to "Ready" (much the same as Visual Studio). How should I wire this together so that I can have the data access code separated out in the ViewModel whilst keeping a responsive UI? I have tried using the BackgroundWorker is various places in the code and I still end up with an unresponsive UI.

    Read the article

  • Silverlight 4 RIA does not return anything using DomainContext

    - by Savvas Sopiadis
    Hi everybody! Just learning Silverlight 4/RIA and i 'm stuck in a weird problem: setup an ASP.NET MVC project as the project hosting the Domain service. In this i tried to get data from the Domain Service which worked fine (i'm using a repository in it). Now i tried to setup a SL4 project. I though i do it the MVVM-way, so i decided to setup a ViewModel Class with the following code: public class ViewModel { OrganizationDomainContext dsCtxt = new OrganizationDomainContext(); public ViewModel() { EntityQuery<Culture> query = from cu in dsCtxt.GetAllCulturesQuery() select cu; LoadOperation<Culture> lo = dsCtxt.Load(query); } } The crazy thing about this is .. it doesn't return anything!!! What am i missing here? Thanks in advance

    Read the article

  • How to stop a WPF binding from ignoring the PropertyChanged event that it caused?

    - by Jacob Stanley
    I have a TextBox bound to a ViewModel's Text property with the following setup: Xaml <TextBox Text="{Binding Text}"/> C# public class ViewModel : INotifyPropertyChanged { public string Text { get { return m_Text; } set { if (String.Equals(m_Text, value)) { return; } m_Text = value.ToLower(); RaisePropertyChanged("Text"); } } // Snip } When I type some stuff in to the TextBox it successfully sets the Text property on the ViewModel. The problem is that WPF ignores the property changed event that is raised by it's own update. This results in the user not seeing the text they typed converted to lowercase. How can I change this behaviour so that the TextBox updates with lowercase text? Note: this is just an example I have used to illustrate the problem of WPF ignoring events. I'm not really interested in converting strings to lowercase or any issues with String.Equals(string, string).

    Read the article

  • How Can I Add a New Command to a Control's Event

    - by Chris
    Hi, thanks for taking a look at this question. I have been building an application (VB/WPF) following Josh Smith's example of an MVVM pattern: Click here to view My Views have Controls which trigger a Command upon an event, such as a button click and these are bound to properties in the ViewModel. My ViewModel exposes properties of type ICommand which invoke the appropriate methods. This has worked well, until now! I now want to use a Thumb Control to allow a user to move an object within a Canvas. I don't believe that the Thumb has a Command capability 'out of the box'. A Thumb raises a 'DragDelta' event when being moved. So my question is as follows: How do I extend a Control's capability to issue a Command upon an event please? I wish to issue a new Command, let's say 'onDragDelta' so that I can bind it to a property in my ViewModel just like my Buttons. Thank you very much

    Read the article

  • Do I need a view controller for MVVM-light in Silverlight?

    - by Stefan de Vogelaere
    I have the following question regarding MVVM light: what "drives" the UI? I see I can have a ViewModel per View I am showing; the ViewLocator handles all the ViewModels (for caching as I understand). But what is driving the UI? If I have a Command defined in my ViewModel that says "ShowDetail"; do I have to write the code for displaying this View inside the ViewModel? Are there any examples of this? Thanks!

    Read the article

  • C# - What should I do when every inherited class needs getter from base class, but setter only for O

    - by msfanboy
    Hello, I have a abstract class called WizardViewModelBase. All my WizardXXXViewModel classes inherit from the base abstract class. The base has a property with a getter. Every sub class needs and overrides that string property as its the DisplayName of the ViewModel. Only ONE ViewModel called WizardTimeTableWeekViewModel needs a setter because I have to set wether the ViewModel is a timetable for week A or week B. Using 2 ViewModels like WizardTimeTableWeekAViewModel and WizardTimeTableWeekBViewModel would be redundant. I do not want to override the setter in all other classes as they do not need a setter. Can I somehow tell the sub class it needs not to override the setter? Or any other suggestion? With interfaces I would be free to use getter or setter but having many empty setter properties is not an option for me.

    Read the article

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