Search Results

Search found 32302 results on 1293 pages for 'model view viewmodel'.

Page 10/1293 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • ASP.Net MVC 2 is it possible to get the same instance of model(with slight changes) in HttpPost meth

    - by jjjjj
    Hi I have a complex entity User: public class User : BaseEntity { public virtual Taxi Taxi { get; set; } --> That is why i call it "complex" public virtual string Login { get; set; } public virtual string Password { get; set; } } where Taxi is a parent of User (Taxi has-many Users): public class Taxi : BaseEntity { public virtual string Name { get; set; } public virtual string ClientIp { get; set; } } BaseEntity consists of public virtual int Id { get; private set; } The problem occurs while trying to edit User [Authorize] public ActionResult ChangeAccountInfo() { var user = UserRepository.GetUser(User.Identity.Name); return View(user); } My ChangeAccountInfo.aspx <fieldset> <legend>Fields</legend> <% %> <div class="editor-label"> <%: Html.LabelFor(model => model.Login) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Login) %> <%: Html.ValidationMessageFor(model => model.Login) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.Password) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Password) %> <%: Html.ValidationMessageFor(model => model.Password) %> </div> <div class="editor-field"> <%: Html.HiddenFor(model => model.Taxi.Name)%> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> Post changes: [Authorize] [HttpPost] public ActionResult ChangeAccountInfo(User model) { if (ModelState.IsValid) { UserRepository.UpdateUser(model); return RedirectToAction("ChangeAccountInfoSuccess", "Account"); } return View(model); } But, the (User model) parameter has User.Id == 0 -- User entity had 5 before edit User.Login == "my new login" User.Password == "my new password" User.Taxi.Id == 0 -- User.Taxi entity had 3 before edit User.Taxi.Name == "old hidden name" User.Taxi.ClientIp == null -- User entity had 192.168.0.1 before edit Q: Is it possible not to mark all the fields of an entity (that should be in my UpdateUser) with tag "hidden" but still have them unchanged in my HttpPost method? e.g. not User.Taxi.ClientIp = null, but User.Taxi.ClientIp = 192.168.0.1 I'm using nhibernate, if it matters.

    Read the article

  • ForEach with EditorFor

    - by hermiod
    I have got an Entity model which contains a collection of Message objects which are of the type Message which has several properties, including content, MessageID, from, and to. I have created an EditorTemplate for type Message, however, I cannot get it to display the contents of the Messages collection. There are no errors, but nothing is output. Please note that the view code is from an EditorTemplate for the parent Talkback class. Can you have an EditorTemplate calling another EditorTemplate for a child collection? Both the Talkback and Message class are generated by Entity framework from an existing database. View code: <% foreach (TalkbackEntityTest.Message msg in Model.Messages) { Html.EditorFor(x=> msg, "Message"); } %> This is my template code. It is the standard auto-generated view code with some minor changes. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TalkbackEntityTest.Message>" %> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%: Html.LabelFor(model => model.MessageID) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.MessageID) %> <%: Html.ValidationMessageFor(model => model.MessageID) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.acad_period) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.acad_period) %> <%: Html.ValidationMessageFor(model => model.acad_period) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.talkback_id) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.talkback_id) %> <%: Html.ValidationMessageFor(model => model.talkback_id) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.From) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.From) %> <%: Html.ValidationMessageFor(model => model.From) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.To) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.To) %> <%: Html.ValidationMessageFor(model => model.To) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.SentDatetime) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.SentDatetime, String.Format("{0:g}", Model.SentDatetime)) %> <%: Html.ValidationMessageFor(model => model.SentDatetime) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.content) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.content) %> <%: Html.ValidationMessageFor(model => model.content) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.MessageTypeID) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.MessageTypeID) %> <%: Html.ValidationMessageFor(model => model.MessageTypeID) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> There is definitely content in the Message collection as, if I remove EditorFor and put in response.write on the content property of the Message class, I get the content field for 3 Message objects on the page, which is exactly as expected.

    Read the article

  • In MVC , DAO should be called from Controller or Model

    - by tito
    I have seen various arguments against the DAO being called from the Controller class directly and also the DAO from the Model class.Infact I personally feel that if we are following the MVC pattern , the controller should not coupled with the DAO , but the Model class should invoke the DAO from within and controller should invoke the model class.Why because , we can decouple the model class apart from a webapplication and expose the functionalities for various ways like for a REST service to use our model class. If we write the DAO invocation in the controller , it would not be possible for a REST service to reuse the functionality right ? I have summarized both the approaches below. Approach #1 public class CustomerController extends HttpServlet { proctected void doPost(....) { Customer customer = new Customer("xxxxx","23",1); new CustomerDAO().save(customer); } } Approach #2 public class CustomerController extends HttpServlet { proctected void doPost(....) { Customer customer = new Customer("xxxxx","23",1); customer.save(customer); } } public class Customer { ........... private void save(Customer customer){ new CustomerDAO().save(customer); } } Note- Here is what a definition of Model is : Model: The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react. I would need an expert opinion on this because I find many using #1 or #2 , So which one is it ?

    Read the article

  • Rogue PropertyChanged notifications from ViewModel

    - by user1886323
    The following simple program is causing me a Databinding headache. I'm new to this which is why I suspect it has a simple answer. Basically, I have two text boxes bound to the same property myString. I have not set up the ViewModel (simply a class with one property, myString) to provide any notifications to the View for when myString is changed, so even although both text boxes operate a two way binding there should be no way that the text boxes update when myString is changed, am I right? Except... In most circumstances this is true - I use the 'change value' button at the bottom of the window to change the value of myString to whatever the user types into the adjacent text box, and the two text boxes at the top, even although they are bound to myString, do not change. Fine. However, if I edit the text in TextBox1, thus changing the value of myString (although only when the text box loses focus due to the default UpdateSourceTrigger property, see reference), TextBox2 should NOT update as it shouldn't receive any updates that myString has changed. However, as soon as TextBox1 loses focus (say click inside TextBox2) TextBox2 is updated with the new value of myString. My best guess so far is that because the TextBoxes are bound to the same property, something to do with TextBox1 updating myString gives TextBox2 a notification that it has changed. Very confusing as I haven't used INotifyPropertyChanged or anything like that. To clarify, I am not asking how to fix this. I know I could just change the binding mode to a oneway option. I am wondering if anyone can come up with an explanation for this strange behaviour? ViewModel: namespace WpfApplication1 { class ViewModel { public ViewModel() { _myString = "initial message"; } private string _myString; public string myString { get { return _myString; } set { if (_myString != value) { _myString = value; } } } } } View: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:ViewModel /> </Window.DataContext> <Grid> <!-- The culprit text boxes --> <TextBox Height="23" HorizontalAlignment="Left" Margin="166,70,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=myString, Mode=TwoWay}" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="166,120,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Path=myString, Mode=TwoWay}"/> <!--The buttons allowing manual change of myString--> <Button Name="changevaluebutton" Content="change value" Click="ButtonUpdateArtist_Click" Margin="12,245,416,43" Width="75" /> <Button Content="Show value" Height="23" HorizontalAlignment="Left" Margin="12,216,0,0" Name="showvaluebutton" VerticalAlignment="Top" Width="75" Click="showvaluebutton_Click" /> <Label Content="" Height="23" HorizontalAlignment="Left" Margin="116,216,0,0" Name="showvaluebox" VerticalAlignment="Top" Width="128" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="116,245,0,0" Name="changevaluebox" VerticalAlignment="Top" Width="128" /> <!--simply some text--> <Label Content="TexBox1" Height="23" HorizontalAlignment="Left" Margin="99,70,0,0" Name="label1" VerticalAlignment="Top" Width="61" /> <Label Content="TexBox2" Height="23" HorizontalAlignment="Left" Margin="99,118,0,0" Name="label2" VerticalAlignment="Top" Width="61" /> </Grid> </Window> Code behind for view: namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { ViewModel viewModel; public MainWindow() { InitializeComponent(); viewModel = (ViewModel)this.DataContext; } private void showvaluebutton_Click(object sender, RoutedEventArgs e) { showvaluebox.Content = viewModel.myString; } private void ButtonUpdateArtist_Click(object sender, RoutedEventArgs e) { viewModel.myString = changevaluebox.Text; } } }

    Read the article

  • How do I use DomainContext.Load in my ViewModel?

    - by kristian
    I'm trying to use RIA services to provide data to my Silverlight application by calling DomainContext.Load to retrieve a collection of widgets. I want to expose this collection through a property of the ViewModel so I can bind a control to the collection in my page. I think my approach must be fundamentally wrong because Load is called asynchronously and is therefore not available when my page loads and the control tried to bind. Can someone please show me the right way to do this? My Silverlight page has the following XAML: <navigation:Page x:Class="Demo.UI.Pages.WidgetPage" // the usual xmlns stuff here... xmlns:local="clr-namespace:Demo.UI.Pages" mc:Ignorable="d" xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation" d:DataContext="{d:DesignInstance Type=local:WidgetPageModel, IsDesignTimeCreatable=False}" d:DesignWidth="640" d:DesignHeight="480" Title="Widget Page"> <Canvas x:Name="LayoutRoot"> <ListBox ItemsSource="{Binding RedWidgets}" Width="150" Height="500" /> </Canvas> </navigation:Page> My ViewModel looks like this: public class WidgetPageModel { private WidgetDomainContext WidgetContext { get; set; } public WidgetPageModel() { this.WidgetContext = new WidgetDomainContext(); WidgetContext.Load(WidgetContext.GetAllWidgetsQuery(), false); } public IEnumerable<Widget> RedWidgets { get { return this.WidgetContext.Widgets.Where(w => w.Colour == "Red"); } } }

    Read the article

  • What is the appropriate granularity in building a ViewModel?

    - by JasCav
    I am working on a new project, and, after seeing some of the difficulties of previous projects that didn't provide enough separation of view from their models (specifically using MVC - the models and views began to bleed into each other a bit), I wanted to use MVVM. I understand the basic concept, and I'm excited to start using it. However, one thing that escapes me a bit - what data should be contained in the ViewModel? For example, if I am creating a ViewModel that will encompass two pieces of data so they can be edited in a form, do I capture it like this: public PersonAddressViewModel { public Person Person { get; set; } public Address Address { get; set; } } or like this: public PersonAddressViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string StreetName { get; set; } // ...etc } To me, the first feels more correct for what we're attempting to do. If we were doing more fine grain forms (maybe all we were capturing was FirstName, LastName, and StreetAddress) then it might make more sense to go down to that level. But, I feel like the first is correct since we're capturing ALL Person data in the form and ALL Address data. It seems like it doesn't make sense (and a lot of extra work) to split things apart like that. Appreciate any insight.

    Read the article

  • Custom model binder for model inner property

    - by Andrej Kaurin
    My model is like this public class MyModel { string ID {get;set;} string Title {get;set;} MyOtherModel Meta {get;set;} } How to define custom model binder for type (MyOtherModel) so when default binder binds MyModel it calls custom model binder for 'Meta' property. I registered it in App start like: ModelBinders.Binders[typeof(MyOtherModel)] = new MyCustomBinder(); but this doesn't work. Any idea or any good article with more infor regarding to model binders?

    Read the article

  • Actor model to replace the threading model?

    - by prosseek
    I read a chapter in a book (Seven languages in Seven Weeks by Bruce A. Tate) about Matz (Inventor of Ruby) saying that 'I would remove the thread and add actors, or some other more advanced concurrency features'. Why and how an actor model can be an advanced concurrency model that replaces the threading? What other models are the 'advanced concurrency model'?

    Read the article

  • How do I reference Django Model from another model

    - by user313943
    Im looking to create a view in the admin panel for a test program which logs Books, publishers and authors (as on djangoproject.com) I have the following two models defined. class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title What I want to do, is change the Book model to reference the first_name of any authors and show this using admin.AdminModels. #Here is the admin model I've created. class BookAdmin(admin.ModelAdmin): list_display = ('title', 'publisher', 'publication_date') # Author would in here list_filter = ('publication_date',) date_hierarchy = 'publication_date' ordering = ('-publication_date',) fields = ('title', 'authors', 'publisher', 'publication_date') filter_horizontal = ('authors',) raw_id_fields = ('publisher',) As I understand it, you cannot have two ForeignKeys in the same model. Can anyone give me an example of how to do this? I've tried loads of different things and its been driving me mad all day. Im pretty new to Python/Django. Just to be clear - I'd simply like the Author(s) First/Last name to appear alongside the book title and publisher name. Thanks

    Read the article

  • Doing large updates against indexed view

    - by user217136
    We have an indexed view that runs across three large tables. Two of these tables (A & B) are constantly getting updated with user transactions and the other table (C) contains data product info that is needs to be updated once a week. This product table contains over 6 million records. We need this view across these three tables for our core business process and unfortunately we cannot change this aspect. We even had a sql server MVP come in to help test under load to make sure we have the most efficient configuration. There is one column in the product table that gets utilized in the view and has to be updated each week. The problem we are now encountering is that as volume is increasing on our transactions against tables A & B, the update to Table C is causing deadlocks. I have tried several different methods to no avail: 1) I was hoping that we could change the view so that table C could be a dirty read "WITH (NOLOCK)" but apparently that functionality is not available with indexes views. 2) I thought about updating a new column in Table C and then just renaming it when the process is done but you cannot do that due to the dependency in the view. 3) I also entertained the idea of writing this value to a temporary product table, and then running an ALTER statement against the view to have it point to my new table. however when i did that the indexes on my view were dropped and it took quite a bit of time to recreate them. 4) we tried to do the weekly update in small chunks (as small as 100 records at a time) but we still run into dead locks. questions: a) we are using sql server 2005. Does sql server 2008 have a new functionality with their indexed views that would help us? Is there now a way to do dirty reads w/ an indexed view? b) a better approach to altering an existing view to point to a new table? thanks!

    Read the article

  • iPhone: Animating a view when another view appears/disappears

    - by MacTouch
    I have the following view hierarchy UITabBarController - UINavigationController - UITableViewController When the table view appears (animated) I create a toolbar and add it as subview of the TabBar at the bottom of the page and let it animate in with the table view. Same procedure in other direction, when the table view disappears. It does not work as expected. The animation duration is OK, but somehow not exact the same as the animation of the table view when it becomes visible When I display the table view for the second time, the toolbar does not disappear at all and remains at the bottom of the parent view. What's wrong with it? - (void)animationDone:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { UIView *toolBar = [[[self tabBarController] view] viewWithTag:1000]; [toolBar removeFromSuperview]; } - (void)viewWillAppear:(BOOL)animated { UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, 44, 0); [[self tableView] setContentInset:insets]; [[self tableView] setScrollIndicatorInsets:insets]; // Toolbar initially placed outside of the visible frame (x=320) UIView *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(320, 480-44, 320, 44)]; [toolBar setTag:1000]; [[[self tabBarController] view] addSubview:toolBar]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:0.35]; [toolBar setFrame:CGRectMake(0, 480-44, 320, 44)]; [UIView commitAnimations]; [toolBar release]; [super viewWillAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { UIView *toolBar = [[[self tabBarController] view] viewWithTag:1000]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:0.35]; [UIView setAnimationDidStopSelector:@selector(animationDone:finished:context:)]; [toolBar setFrame:CGRectMake(320, 480-44, 320, 44)]; [UIView commitAnimations]; [super viewWillDisappear:animated]; }

    Read the article

  • How to define one-to-many connection between a same model through another model

    - by Mekajiki
    I want to define one-to-many relationship as follows; User has one introducer User has many newcomers(who is introduced by the user) Use "Introduction" model instead of adding a column to users table. My table and model definition is as follows; DB Scheme: create_table "introductions", force: true do |t| t.integer "introducer_id" t.integer "newcomer_id" t.datetime "created_at" t.datetime "updated_at" User model: class User < ActiveRecord::Base has_many :introductions, foreign_key: :introducer_id has_many :newcomers, through: :introductions, source: :newcomer belongs_to :introduction, foreign_key: :newcomer_id belongs_to :introducer end Introduction model: class Introduction < ActiveRecord::Base belongs_to :introducer, class_name: 'User' belongs_to :newcomer, class_name: 'User' end This works fine: user1.newcomers.push user2 but, user2.introducer # => nil How can I define belongs_to relationship correctly?

    Read the article

  • iPhone View Switching basics.

    - by Daniel Granger
    I am just trying to get my head around simple view switching for the iPhone and have created a simple app to try and help me understand it. I have included the code from my root controller used to switch the views. My app has a single toolbar with three buttons on it each linking to one view. Here is my code to do this but I think there most be a more efficient way to achieve this? Is there a way to find out / remove the current displayed view instead of having to do the if statements to see if either has a superclass? I know I could use a tab bar to create a similar effect but I am just using this method to help me practice a few of the techniques. -(IBAction)switchToDataInput:(id)sender{ if (self.dataInputVC.view.superview == nil) { if (dataInputVC == nil) { dataInputVC = [[DataInputViewController alloc] initWithNibName:@"DataInput" bundle:nil]; } if (self.UIElementsVC.view.superview != nil) { [UIElementsVC.view removeFromSuperview]; } else if (self.totalsVC.view.superview != nil) { [totalsVC.view removeFromSuperview]; } [self.view insertSubview:dataInputVC.view atIndex:0]; } } -(IBAction)switchToUIElements:(id)sender{ if (self.UIElementsVC.view.superview == nil) { if (UIElementsVC == nil) { UIElementsVC = [[UIElementsViewController alloc] initWithNibName:@"UIElements" bundle:nil]; } if (self.dataInputVC.view.superview != nil) { [dataInputVC.view removeFromSuperview]; } else if (self.totalsVC.view.superview != nil) { [totalsVC.view removeFromSuperview]; } [self.view insertSubview:UIElementsVC.view atIndex:0]; } } -(IBAction)switchToTotals:(id)sender{ if (self.totalsVC.view.superview == nil) { if (totalsVC == nil) { totalsVC = [[TotalsViewController alloc] initWithNibName:@"Totals" bundle:nil]; } if (self.dataInputVC.view.superview != nil) { [dataInputVC.view removeFromSuperview]; } else if (self.UIElementsVC.view.superview != nil) { [UIElementsVC.view removeFromSuperview]; } [self.view insertSubview:totalsVC.view atIndex:0]; } }

    Read the article

  • accessing view controller's view

    - by Mike
    I am inside a class on a view-based app, one that was creating with one view controller. WHen I am inside the view controller I can access its view using self.view, but how do I access the same view if I am inside a class? [[UIApplication sharedApplication] delegate]... //??? what do I put here? thanks

    Read the article

  • MVC Rendered Partial, how to get partial/view model in main model post to controller

    - by user1475788
    I have a text file and when users upload the file, the controller action method parses that file using state machine and uses a generic list to store some values. I pass this back to the view in the form of an IEnumerable. Within my main view, based on this ienumerable list I render a partail view to iterate items and display labels and a textarea. Users could add their input in the text area. When the users hit the save button this ienumrable list from the partial view rendered is null. so please advice any solutions. here is my main view @model RunLog.Domain.Entities.RunLogEntry @{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } @using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div id="inputTestExceptions" style="display: none;"> <table class="grid" style="width: 450px; margin: 3px 3px 3px 3px;"> <thead> <tr> <th> Exception String </th> <th> Comment </th> </tr> </thead> <tbody> @if (Model.TestExceptions != null) { foreach (var p in Model.TestExceptions) { Html.RenderPartial("RunLogTestExceptionSummary", p); } } </tbody> </table> </div> } partial view as follows: @model RunLog.Domain.Entities.RunLogEntryTestExceptionDisplay <tr> <td> @Model.TestException@ </td> <td>@Html.TextAreaFor(Model.Comment, new { style = "width: 200px; height: 80px;" }) </td> </tr> Controller action [HttpPost] public ActionResult Create(RunLogEntry runLogEntry, String ServiceRequest, string Hour, string Minute, string AMPM, string submit, IEnumerable<HttpPostedFileBase> file, String AssayPerformanceIssues1, IEnumerable<RunLogEntryTestExceptionDisplay> models) { } The problem is test exceptions which contains exception string and comment is comming back null.

    Read the article

  • Using a join model to relate a model to itself

    - by Gabe Hollombe
    I have two models: User MentoringRelationship MentoringRelationship is a join model that has a mentor_id column and a mentee_id column (both of these reference user_ids from the users table). How can I specify a relation called 'mentees' on the User class that will return all of the users mentored by this user, using the MentoringRelationships join table? What relations do we need to declare in the User model and in the MentoringRelationship model?

    Read the article

  • What is good practice in .NET system architecture design concerning multiple models and aggregates

    - by BuzzBubba
    I'm designing a larger enterprise architecture and I'm in a doubt about how to separate the models and design those. There are several points I'd like suggestions for: - models to define - way to define models Currently my idea is to define: Core (domain) model Repositories to get data to that domain model from a database or other store Business logic model that would contain business logic, validation logic and more specific versions of forms of data retrieval methods View models prepared for specifically formated data output that would be parsed by views of different kind (web, silverlight, etc). For the first model I'm puzzled at what to use and how to define the mode. Should this model entities contain collections and in what form? IList, IEnumerable or IQueryable collections? - I'm thinking of immutable collections which IEnumerable is, but I'd like to avoid huge data collections and to offer my Business logic layer access with LINQ expressions so that query trees get executed at Data level and retrieve only really required data for situations like the one when I'm retrieving a very specific subset of elements amongst thousands or hundreds of thousands. What if I have an item with several thousands of bids? I can't just make an IEnumerable collection of those on the model and then retrieve an item list in some Repository method or even Business model method. Should it be IQueryable so that I actually pass my queries to Repository all the way from the Business logic model layer? Should I just avoid collections in my domain model? Should I void only some collections? Should I separate Domain model and BusinessLogic model or integrate those? Data would be dealt trough repositories which would use Domain model classes. Should repositories be used directly using only classes from domain model like data containers? This is an example of what I had in mind: So, my Domain objects would look like (e.g.) public class Item { public string ItemName { get; set; } public int Price { get; set; } public bool Available { get; set; } private IList<Bid> _bids; public IQueryable<Bid> Bids { get { return _bids.AsQueryable(); } private set { _bids = value; } } public AddNewBid(Bid newBid) { _bids.Add(new Bid {.... } } Where Bid would be defined as a normal class. Repositories would be defined as data retrieval factories and used to get data into another (Business logic) model which would again be used to get data to ViewModels which would then be rendered by different consumers. I would define IQueryable interfaces for all aggregating collections to get flexibility and minimize data retrieved from real data store. Or should I make Domain Model "anemic" with pure data store entities and all collections define for business logic model? One of the most important questions is, where to have IQueryable typed collections? - All the way from Repositories to Business model or not at all and expose only solid IList and IEnumerable from Repositories and deal with more specific queries inside Business model, but have more finer grained methods for data retrieval within Repositories. So, what do you think? Have any suggestions?

    Read the article

  • Routing to a Controller with no View in Angular

    - by Rick Strahl
    I've finally had some time to put Angular to use this week in a small project I'm working on for fun. Angular's routing is great and makes it real easy to map URL routes to controllers and model data into views. But what if you don't actually need a view, if you effectively need a headless controller that just runs code, but doesn't render a view?Preserve the ViewWhen Angular navigates a route and and presents a new view, it loads the controller and then renders the view from scratch. Views are not cached or stored, but displayed and then removed. So if you have routes configured like this:'use strict'; // Declare app level module which depends on filters, and services window.myApp = angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers']). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/map', { template: "partials/map.html ", controller: 'mapController', reloadOnSearch: false, animation: 'slide' }); … $routeProvider.otherwise({redirectTo: '/map'}); }]); Angular routes to the mapController and then re-renders the map.html template with the new data from the $scope filled in.But, but… I don't want a new View!Now in most cases this works just fine. If I'm rendering plain DOM content, or textboxes in a form interface that is all fine and dandy - it's perfectly fine to completely re-render the UI.But in some cases, the UI that's being managed has state and shouldn't be redrawn. In this case the main page in question has a Google Map on it. The map is  going to be manipulated throughout the lifetime of the application and the rest of the pages. In my application I have a toolbar on the bottom and the rest of the content is replaced/switched out by the Angular Views:The problem is that the map shouldn't be redrawn each time the Location view is activated. It should maintain its state, such as the current position selected (which can move), and shouldn't redraw due to the overhead of re-rendering the initial map.Originally I set up the map, exactly like all my other views - as a partial, that is rendered with a separate file, but that didn't work.The Workaround - Controller Only RoutesThe workaround for this goes decidedly against Angular's way of doing things:Setting up a Template-less RouteIn-lining the map view directly into the main pageHiding and showing the map view manuallyLet's see how this works.Controller Only RouteThe template-less route is basically a route that doesn't have any template to render. This is not directly supported by Angular, but thankfully easy to fake. The end goal here is that I want to simply have the Controller fire and then have the controller manage the display of the already active view by hiding and showing the map and any other view content, in effect bypassing Angular's view display management.In short - I want a controller action, but no view rendering.The controller-only or template-less route looks like this: $routeProvider.when('/map', { template: " ", // just fire controller controller: 'mapController', animation: 'slide' });Notice I'm using the template property rather than templateUrl (used in the first example above), which allows specifying a string template, and leaving it blank. The template property basically allows you to provide a templated string using Angular's HandleBar like binding syntax which can be useful at times. You can use plain strings or strings with template code in the template, or as I'm doing here a blank string to essentially fake 'just clear the view'. In-lined ViewSo if there's no view where does the HTML go? Because I don't want Angular to manage the view the map markup is in-lined directly into the page. So instead of rendering the map into the Angular view container, the content is simply set up as inline HTML to display as a sibling to the view container.<div id="MapContent" data-icon="LocationIcon" ng-controller="mapController" style="display:none"> <div class="headerbar"> <div class="right-header" style="float:right"> <a id="btnShowSaveLocationDialog" class="iconbutton btn btn-sm" href="#/saveLocation" style="margin-right: 2px;"> <i class="icon-ok icon-2x" style="color: lightgreen; "></i> Save Location </a> </div> <div class="left-header">GeoCrumbs</div> </div> <div class="clearfix"></div> <div id="Message"> <i id="MessageIcon"></i> <span id="MessageText"></span> </div> <div id="Map" class="content-area"> </div> </div> <div id="ViewPlaceholder" ng-view></div>Note that there's the #MapContent element and the #ViewPlaceHolder. The #MapContent is my static map view that is always 'live' and is initially hidden. It is initially hidden and doesn't get made visible until the MapController controller activates it which does the initial rendering of the map. After that the element is persisted with the map data already loaded and any future access only updates the map with new locations/pins etc.Note that default route is assigned to the mapController, which means that the mapController is fired right as the page loads, which is actually a good thing in this case, as the map is the cornerstone of this app that is manipulated by some of the other controllers/views.The Controller handles some UISince there's effectively no view activation with the template-less route, the controller unfortunately has to take over some UI interaction directly. Specifically it has to swap the hidden state between the map and any of the other views.Here's what the controller looks like:myApp.controller('mapController', ["$scope", "$routeParams", "locationData", function($scope, $routeParams, locationData) { $scope.locationData = locationData.location; $scope.locationHistory = locationData.locationHistory; if ($routeParams.mode == "currentLocation") { bc.getCurrentLocation(false); } bc.showMap(false,"#LocationIcon"); }]);bc.showMap is responsible for a couple of display tasks that hide/show the views/map and for activating/deactivating icons. The code looks like this:this.showMap = function (hide,selActiveIcon) { if (!hide) $("#MapContent").show(); else { $("#MapContent").hide(); } self.fitContent(); if (selActiveIcon) { $(".iconbutton").removeClass("active"); $(selActiveIcon).addClass("active"); } };Each of the other controllers in the app also call this function when they are activated to basically hide the map and make the View Content area visible. The map controller makes the map.This is UI code and calling this sort of thing from controllers is generally not recommended, but I couldn't figure out a way using directives to make this work any more easily than this. It'd be easy to hide and show the map and view container using a flag an ng-show, but it gets tricky because of scoping of the $scope. I would have to resort to storing this setting on the $rootscope which I try to avoid. The same issues exists with the icons.It sure would be nice if Angular had a way to explicitly specify that a View shouldn't be destroyed when another view is activated, so currently this workaround is required. Searching around, I saw a number of whacky hacks to get around this, but this solution I'm using here seems much easier than any of that I could dig up even if it doesn't quite fit the 'Angular way'.Angular nice, until it's notOverall I really like Angular and the way it works although it took me a bit of time to get my head around how all the pieces fit together. Once I got the idea how the app/routes, the controllers and views snap together, putting together Angular pages becomes fairly straightforward. You can get quite a bit done never going beyond those basics. For most common things Angular's default routing and view presentation works very well.But, when you do something a bit more complex, where there are multiple dependencies or as in this case where Angular doesn't appear to support a feature that's absolutely necessary, you're on your own. Finding information on more advanced topics is not trivial especially since versions are changing so rapidly and the low level behaviors are changing frequently so finding something that works is often an exercise in trial and error. Not that this is surprising. Angular is a complex piece of kit as are all the frameworks that try to hack JavaScript into submission to do something that it was really never designed to. After all everything about a framework like Angular is an elaborate hack. A lot of shit has to happen to make this all work together and at that Angular (and Ember, Durandel etc.) are pretty amazing pieces of JavaScript code. So no harm, no foul, but I just can't help feeling like working in toy sandbox at times :-)© Rick Strahl, West Wind Technologies, 2005-2013Posted in Angular  JavaScript   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="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Simple ViewModel Locator for MVVM: The Patients Have Left the Asylum

    Ive been toying with some ideas for MVVM lately. Along the way I have been dragging some friends like Glenn Block and Ward Bell along for the ride. Now, normally its not so bad, but when I get an idea in my head to challenge everything I can be interesting to work with :). These guys are great and I highly encourage you all to get your own personal Glenn and Ward bobble head dolls for your home. But back to MVVM Ive been exploring the world of View first again. The idea is simple: the View is created,...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

  • Simple ViewModel Locator for MVVM: The Patients Have Left the Asylum

    Ive been toying with some ideas for MVVM lately. Along the way I have been dragging some friends like Glenn Block and Ward Bell along for the ride. Now, normally its not so bad, but when I get an idea in my head to challenge everything I can be interesting to work with :). These guys are great and I highly encourage you all to get your own personal Glenn and Ward bobble head dolls for your home. But back to MVVM Ive been exploring the world of View first again. The idea is simple: the View is created,...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

  • A really simple ViewModel base class with strongly-typed INotifyPropertyChanged

    - by Daniel Cazzulino
    I have already written about other alternative ways of implementing INotifyPropertyChanged, as well as augment your view models with a bit of automatic code generation for the same purpose. But for some co-workers, either one seemed a bit too much :o). So, back on the drawing board, we came up with the following view model authoring experience:public class MyViewModel : ViewModel, IExplicitInterface { private int value; public int Value { get { return value; } set { this.value = value; RaiseChanged(() =&gt; this.Value); } } double IExplicitInterface.DoubleValue { get { return value; } set { this.value = (int)value; RaiseChanged(() =&gt; ((IExplicitInterface)this).DoubleValue); } } } ...Read full article

    Read the article

  • Custom ViewModel with MVC 2 Strongly Typed HTML Helpers return null object on Create ?

    - by Barbaros Alp
    Hi, I am having a trouble while trying to create an entity with a custom view modeled create form. Below is my custom view model for Category Creation form. public class CategoryFormViewModel { public CategoryFormViewModel(Category category, string actionTitle) { Category = category; ActionTitle = actionTitle; } public Category Category { get; private set; } public string ActionTitle { get; private set; } } and this is my user control where the UI is <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CategoryFormViewModel>" %> <h2> <span><%= Html.Encode(Model.ActionTitle) %></span> </h2> <%=Html.ValidationSummary() %> <% using (Html.BeginForm()) {%> <p> <span class="bold block">Baslik:</span> <%=Html.TextBoxFor(model => Model.Category.Title, new { @class = "width80 txt-base" })%> </p> <p> <span class="bold block">Sira Numarasi:</span> <%=Html.TextBoxFor(model => Model.Category.OrderNo, new { @class = "width10 txt-base" })%> </p> <p> <input type="submit" class="btn-admin cursorPointer" value="Save" /> </p> <% } %> When i click on save button, it doesnt bind the category for me because of i am using custom view model and strongly typed html helpers like that <%=Html.TextBoxFor(model => Model.Category.OrderNo) %> How can i fix this ? Thanks in advance

    Read the article

  • Using GPO to collect data about VMware view activity

    - by MoSiAc
    Our security group wants us to begin logging data for external access to our view enviroment. At first we thought that view security would be logging all source ip's that are external in nature so if for some reason there is an intrusion we would have record of it there. Of course our firewall logs all that information but correlating it to view is sketchy at best with our current implementation. We know on viewdesktops there is a set of keys in VolitateEnviroment that contains stuff such as source ip and username, etc. We have a script in place that, when run as a logon script attached to a user account in AD collects the information as we need it. If we have a GPO run the same script the information does not get collected. We feel like there is a piece of the puzzle we're missing but we don't know what. If anyone knows what we're forgetting or misconfiguring that would be great, or if you have a better way of us collecting external source ip's for view specifically we'd be interested in that as well. Thanks, EDIT CODE Batch script to dump to text file @echo off timeout 20 echo %computername%/%username% %time% %date% c:\vdi\vmware.txt echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c:\vdi\vmware.txt reg query "HKEY_CURRENT_USER\Volatile Environment" /v "ViewClient_LoggedOn_Username"c:\vdi\vmware.txt reg query "HKEY_CURRENT_USER\Volatile Environment" /v "ViewClient_IP_Address"c:\vdi\vmware.txt echo.c:\vdi\vmware.txt VB Script to display values Const HKEY_CURRENT_USER = &H80000001 Set wmiLocator=CreateObject("WbemScripting.SWbemLocator") Set wmiNameSpace = wmiLocator.ConnectServer(".", "root\default") Set objRegistry = wmiNameSpace.Get("StdRegProv") sPath = "Volatile Environment" lRC = objRegistry.GetStringValue(HKEY_CURRENT_USER, sPath, "ViewClien_Machine_Name", vMachine) lRC = objRegistry.GetStringValue(HKEY_CURRENT_USER, sPath, "ViewClien_IP_Address", vIP) lRC = objRegistry.GetStringValue(HKEY_CURRENT_USER, sPath, "ViewClien_MAC_Address", vMAC) msgbox "The Remote Device Name is " & vMachine & " @ " & vIP & " (" & vMAC & ") " he wanted me to mention that the batch file actually runs and I can see it counting down when I reconnect but it does not grab the registry values.

    Read the article

  • ASP.NET MVC 2 Mdel encapsulated within ViewModel Validation

    - by Program.X
    I am trying to get validation to work in ASP.NET MVC 2, but without much success. I have a complex class containing a large number of fields. (Don't ask - this is oneo f those real-world situations best practices can't touch) This would normally be my Model and is a LINQ-to-SQL generated class. Because this is generated code, I have created a MetaData class as per http://davidhayden.com/blog/dave/archive/2009/08/10/AspNetMvc20BuddyClassesMetadataType.aspx. public class ConsultantRegistrationMetadata { [DisplayName("Title")] [Required(ErrorMessage = "Title is required")] [StringLength(10, ErrorMessage = "Title cannot contain more than 10 characters")] string Title { get; set; } [Required(ErrorMessage = "Forename(s) is required")] [StringLength(128, ErrorMessage = "Forename(s) cannot contain more than 128 characters")] [DisplayName("Forename(s)")] string Forenames { get; set; } // ... I've attached this to the partial class of my generated class: [MetadataType(typeof(ConsultantRegistrationMetadata))] public partial class ConsultantRegistration { // ... Because my form is complex, it has a number of dependencies, such as SelectLists, etc. which I have encapsulated in a ViewModel pattern - and included the ConsultantRegistration model as a property: public class ConsultantRegistrationFormViewModel { public Data.ConsultantRegistration ConsultantRegistration { get; private set; } public SelectList Titles { get; private set; } public SelectList Countries { get; private set; } // ... So it is essentially ViewModel=Model My View then has: <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Title) %> <%: Html.DropDownListFor(model => model.ConsultantRegistration.Title, Model.Titles,"(select a Title)") %> <%: Html.ValidationMessage("Title","*") %> </p> <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.TextBoxFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.ValidationMessageFor(model=>model.ConsultantRegistration.Forenames) %> </p> The problem is, the validation attributes on the metadata class are having no effect. I tried doing it via an Interface, but also no effect. I'm beginning to think that the reason is because I am encapsulating my model within a ViewModel. My Controller (Create Action) is as follows: [HttpPost] public ActionResult Create(Data.ConsultantRegistration consultantRegistration) { if (ModelState.IsValid) // this is always true - which is wrong!! { try { consultantRegistration = ConsultantRegistrationRepository.SaveConsultantRegistration(consultantRegistration); return RedirectToAction("Edit", new { id = consultantRegistration.ID, sectionIndex = 2 }); } catch (Exception ex) { ModelState.AddModelError("CreateException",ex); } } return View(new ConsultantRegistrationFormViewModel(consultantRegistration)); } As outlined in the comment, the ModelState.IsValid property always returns true, despite fields with the Validaiton annotations not being valid. (Forenames being a key example). Am I missing something obvious - considering I am an MVC newbie? I'm after the mechanism demoed by Jon Galloway at http://www.asp.net/learn/mvc-videos/video-10082.aspx. (Am aware t is similar to http://stackoverflow.com/questions/1260562/asp-net-mvc-model-viewmodel-validation but that post seems to talk about xVal. I have no idea what that is and suspect it is for MVC 1)

    Read the article

  • ASP.NET MVC 2 Model encapsulated within ViewModel Validation

    - by Program.X
    I am trying to get validation to work in ASP.NET MVC 2, but without much success. I have a complex class containing a large number of fields. (Don't ask - this is oneo f those real-world situations best practices can't touch) This would normally be my Model and is a LINQ-to-SQL generated class. Because this is generated code, I have created a MetaData class as per http://davidhayden.com/blog/dave/archive/2009/08/10/AspNetMvc20BuddyClassesMetadataType.aspx. public class ConsultantRegistrationMetadata { [DisplayName("Title")] [Required(ErrorMessage = "Title is required")] [StringLength(10, ErrorMessage = "Title cannot contain more than 10 characters")] string Title { get; set; } [Required(ErrorMessage = "Forename(s) is required")] [StringLength(128, ErrorMessage = "Forename(s) cannot contain more than 128 characters")] [DisplayName("Forename(s)")] string Forenames { get; set; } // ... I've attached this to the partial class of my generated class: [MetadataType(typeof(ConsultantRegistrationMetadata))] public partial class ConsultantRegistration { // ... Because my form is complex, it has a number of dependencies, such as SelectLists, etc. which I have encapsulated in a ViewModel pattern - and included the ConsultantRegistration model as a property: public class ConsultantRegistrationFormViewModel { public Data.ConsultantRegistration ConsultantRegistration { get; private set; } public SelectList Titles { get; private set; } public SelectList Countries { get; private set; } // ... So it is essentially ViewModel=Model My View then has: <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Title) %> <%: Html.DropDownListFor(model => model.ConsultantRegistration.Title, Model.Titles,"(select a Title)") %> <%: Html.ValidationMessage("Title","*") %> </p> <p> <%: Html.LabelFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.TextBoxFor(model => model.ConsultantRegistration.Forenames) %> <%: Html.ValidationMessageFor(model=>model.ConsultantRegistration.Forenames) %> </p> The problem is, the validation attributes on the metadata class are having no effect. I tried doing it via an Interface, but also no effect. I'm beginning to think that the reason is because I am encapsulating my model within a ViewModel. My Controller (Create Action) is as follows: [HttpPost] public ActionResult Create(Data.ConsultantRegistration consultantRegistration) { if (ModelState.IsValid) // this is always true - which is wrong!! { try { consultantRegistration = ConsultantRegistrationRepository.SaveConsultantRegistration(consultantRegistration); return RedirectToAction("Edit", new { id = consultantRegistration.ID, sectionIndex = 2 }); } catch (Exception ex) { ModelState.AddModelError("CreateException",ex); } } return View(new ConsultantRegistrationFormViewModel(consultantRegistration)); } As outlined in the comment, the ModelState.IsValid property always returns true, despite fields with the Validaiton annotations not being valid. (Forenames being a key example). Am I missing something obvious - considering I am an MVC newbie? I'm after the mechanism demoed by Jon Galloway at http://www.asp.net/learn/mvc-videos/video-10082.aspx. (Am aware t is similar to http://stackoverflow.com/questions/1260562/asp-net-mvc-model-viewmodel-validation but that post seems to talk about xVal. I have no idea what that is and suspect it is for MVC 1)

    Read the article

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