Search Results

Search found 12952 results on 519 pages for 'model'.

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

  • Oracle Communications Data Model

    - by jean-pierre.dijcks
    I've mentioned OCDM in previous posts but found the following (see end of the post) podcast on the topic and figured it is worthwhile to spread the news some more. ORetailDM and OCommunicationsDM are the two data models currently available from Oracle. Both are intended to capture: Business best practices and industry knowledge Pre-built advanced analytics intended to predict future events before they happen (like the Churn model shown below) Oracle technology best practices to ensure optimal performance of the model All of this typically comes with a reduced time to implementation, or as the marketing slogan goes, reduced time to value. Here are the links: Podcast on OCDM OTN pages for OCDM and ORDM

    Read the article

  • Architecting multi-model multi-DB ASP.NET MVC solution

    - by A. Murray
    I have an ASP.NET MVC 4 solution that I'm putting together, leveraging IoC and the repository pattern using Entity Framework 5. I have a new requirement to be able to pull data from a second database (from another internal application) which I don't have control over. There is no API available unfortunately for the second application and the general pattern at my place of work is to go direct to the database. I want to maintain a consistent approach to modeling the domain and use entity framework to pull the data out, so thus far I have used Entity Framework's database first approach to generate a domain model and database context over the top of this. However, I've become a little stuck on how to include the second domain model in the application. I have a generic repository which I've now moved out to a common DataAccess project, but short of creating two distinct wrappers for the generic repository (so each can identify with a specific database context), I'm struggling to see how I can elegantly include multiple models?

    Read the article

  • Trying to Nullify Django model fields with method where model and fields are parameters

    - by Johnny4000
    I'm trying to write a method like the below where a list of fields (a subset of all the fields) is passed in as a parameter and has their column values set to null. I would be happy of I could get a method with just the fields as a parameter like below, but having the model as a parameter would be even better. from my_project.my_app.models import MyModel def nullify_columns (self, null_fields): field_names = MyModel._meta.get_all_field_names() for field in field_names: if field in null_fields: # The below line does not work because I'm not sure how to # dynamically assign the field name. MyModel.objects.all().update( (MyModel.get_field(field).column) = None) Right now I have something like if 'column1' in list_of_fields: MyModel.objects.all().update(column1 = None) if 'column2' in list_of_fields: MyModel.objects.all().update(column2 = None) etc. which is horrible, but works.

    Read the article

  • Create Rails model with argument of associated model?

    - by Kyle Carlson
    I have two models, User and PushupReminder, and a method create_a_reminder in my PushupReminder controller (is that the best place to put it?) that I want to have create a new instance of a PushupReminder for a given user when I pass it a user ID. I have the association via the user_id column working correctly in my PushupReminder table and I've tested that I can both create reminders & send the reminder email correctly via the Rails console. Here is a snippet of the model code: class User < ActiveRecord::Base has_many :pushup_reminders end class PushupReminder < ActiveRecord::Base belongs_to :user end And the create_a_reminder method: def create_a_reminder(user) @user = User.find(user) @reminder = PushupReminder.create(:user_id => @user.id, :completed => false, :num_pushups => @user.pushups_per_reminder, :when_sent => Time.now) PushupReminderMailer.reminder_email(@user).deliver end I'm at a loss for how to run that create_a_reminder method in my code for a given user (eventually will be in a cron job for all my users). If someone could help me get my thinking on the right track, I'd really appreciate it. Thanks!

    Read the article

  • Erfolgreich durchstarten als Partner mit dem Open Market Model

    - by A&C Redaktion
    Wer als Oracle Partner bei dem erfolgreichen Programm OMM (Open Market Model) mitmacht, profitiert vierfach: Projektschutz oder Tipp-Provision, auf der Basis der OMM-Policy "Guter Name" durch kontinuierliche Projektregistrierungen Jedes erfolgreiche OMM-Projekt zählt einen Transaktionspunkt Direkter Ansprechpartner, der OMM Manager als Vermittler zum Oracle Sales Gönnen Sie sich diese 3 Minuten und Sie wissen dann, warum OMM auch für Sie interessant sein kann!

    Read the article

  • Best practice to handle Parent Form Child Form relation using Presentation Model

    - by Rajarshi
    According to Presentation Model notes by Martin Fowler and also on MSDN documentation about Presentation Model, it is explained that the Presentation Model Class should be unaware of the UI class and similarly Business Model Class should be unaware of the Presentation Model class. The UI should databind extensively to the Presentation Model, the Presentation Model in turn will co-ordinate with one or more Domain/Business Model objects to get the job done. The Presentation Model basically presents the Domain Model data in a way to facilitate maximum data binding in UI, allowing the UI take as less decisions as possible and thus increase testability of Presentation behaviours. This also makes the presentation model class generic, i.e. agnostic of any particular UI technology. Now, consider there is a List form (say CustomerList) and there is another Root form (say Customer) and there is a Use Case of allowing to Edit a Customer from the CustomerList form on a button click. For simplicity of discussion, consider that some actions took place when Customer List is opened from menu (i.e. Customer menu clicked) and the Customer List has been shown from the Menu click event. Now as per the above Use Case, I need to open the Customer Root UI (single Customer) from the Customer List. How do I do that? Build necessary objects (BusinessModel, PresentationModel, UI) in click event of Edit button and call CustomerEdit UI from there? Build the CustomerEdit UI from Presentation Model Class and show UI from presentation model? this can be done in any of the two ways below - a. Create objects in the following sequence DomainModel-PresentationModel-UIForm b. Use Unity.Resolve(); Either ways, Presentation Model is violated as the P model now has to the refer the concrete UI assembly, where CustomerEdit is located. Also the P Model has to refer and use a WinForm directly making it less UI technology agnostic. Even though the violations are in theory and can be ignored, I would still seek the community's opinion about whether I am going wrong direction. Please suggest if there's a better way to call the Child Form from the List (Parent) Form. Rajarshi

    Read the article

  • Mapping between 4+1 architectural view model & UML

    - by Sadeq Dousti
    I'm a bit confused about how the 4+1 architectural view model maps to UML. Wikipedia gives the following mapping: Logical view: Class diagram, Communication diagram, Sequence diagram. Development view: Component diagram, Package diagram Process view: Activity diagram Physical view: Deployment diagram Scenarios: Use-case diagram The paper Role of UML Sequence Diagram Constructs in Object Lifecycle Concept gives the following mapping: Logical view (class diagram (CD), object diagram (OD), sequence diagram (SD), collaboration diagram (COD), state chart diagram (SCD), activity diagram (AD)) Development view (package diagram, component diagram), Process view (use case diagram, CD, OD, SD, COD, SCD, AD), Physical view (deployment diagram), and Use case view (use case diagram, OD, SD, COD, SCD, AD) which combines the four mentioned above. The web page UML 4+1 View Materials presents the following mapping: Finally, the white paper Applying 4+1 View Architecture with UML 2 gives yet another mapping: Logical view class diagrams, object diagrams, state charts, and composite structures Process view sequence diagrams, communication diagrams, activity diagrams, timing diagrams, interaction overview diagrams Development view component diagrams Physical view deployment diagram Use case view use case diagram, activity diagrams I'm sure further search will reveal other mappings as well. While various people usually have different perspectives, I don't see why this is the case here. Specially, each UML diagram describes the system from a particular aspect. So, for instance, why the "sequence diagram" is considered as describing the "logical view" of the system by one author, while another author considers it as describing the "process view"? Could you please help me clarify the confusion?

    Read the article

  • LLBLGen Pro feature highlights: model views

    - by FransBouma
    (This post is part of a series of posts about features of the LLBLGen Pro system) To be able to work with large(r) models, it's key you can view subsets of these models so you can have a better, more focused look at them. For example because you want to display how a subset of entities relate to one another in a different way than the list of entities. LLBLGen Pro offers this in the form of Model Views. Model Views are views on parts of the entity model of a project, and the subsets are displayed in a graphical way. Additionally, one can add documentation to a Model View. As Model Views are displaying parts of the model in a graphical way, they're easier to explain to people who aren't familiar with entity models, e.g. the stakeholders you're interviewing for your project. The documentation can then be used to communicate specifics of the elements on the model view to the developers who have to write the actual code. Below I've included an example. It's a model view on a subset of the entities of AdventureWorks. It displays several entities, their relationships (both relational and inheritance relationships) and also some specifics gathered from the interview with the stakeholder. As the information is inside the actual project the developer will work with, the information doesn't have to be converted back/from e.g .word documents or other intermediate formats, it's the same project. This makes sure there are less errors / misunderstandings. (of course you can hide the docked documentation pane or dock it to another corner). The Model View can contain entities which are placed in different groups. This makes it ideal to group entities together for close examination even though they're stored in different groups. The Model View is a first-class citizen of the code-generator. This means you can write templates which consume Model Views and generate code accordingly. E.g. you can write a template which generates a service per Model View and exposes the entities in the Model View as a single entity graph, fetched through a method. (This template isn't included in the LLBLGen Pro package, but it's easy to write it up yourself with the built-in template editor). Viewing an entity model in different ways is key to fully understand the entity model and Model Views help with that.

    Read the article

  • How to disabled the input,textarea,select using this code..

    - by kumar
    Hello friends I am using this code in my view.. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NorthernTrust.ATP.iTool.Core.Business.Entities.Exceptions.PricingMassEditBE>" %> <script type="text/javascript"> $("#PricingEditExceptions").find("input, select,textarea").attr('disabled', 'disabled'); </script> <%var a = Model; %> <fieldset id="PricingEditExceptions"> <div class="fiveper"> <label>FM#: <span><%=(null != a) ? Model.Asset.FundmasterSec : null%></span></label> <label>TNT#:<span><%=(null != a) ? Model.Asset.TNTSecurity: null%></span></label> <label>CUSIP#: <span><%=(null != a) ? Model.Asset.CUSIP :null%></span></label> <label>Asset:<span><%=(null != a) ? Model.Asset.AssetClassCode: null%></span></label> <label>Issue:<span><%=(null != a) ? Model.Asset.IssueType: null%></span></label> <label>COQ:<span><%=(null != a) ? Model.Asset.CodeCountryofQuotationName: null%></span></label> <label>CCY:<span><%=(null != a) ? Model.Asset.CurrencyCode: null%></span></label> <label>&nbsp;</label> </div> <div class="fiveper"> <input id="check1" type="checkbox" name="PMchk" value="<%=Model.ExceptionID%>" /> <label>ID#: <span><%=(null != a) ? Model.ExceptionID : 0%></span></label> <label for="ExceptionStatus"> Status: <span id="gui-stat-<%=Model.ExceptionID %>"> <%=Model.LookupCodes["C_EXCPT_STAT"].FirstOrDefault(model => model.Key.Trim().Equals(Model.ExceptionStatus.Trim())).Value%></span> </label> <label for="ResolutionCode"> Resolution: <span> <%=Html.DropDownListFor(model => model.ResolutionCode, new SelectList(Model.LookupCodes["C_EXCPT_RESL"], "Key", "Value", (null != Model.ResolutionCode) ? Model.ResolutionCode.Trim() : Model.ResolutionCode))%> </span> </label> <label for="ReasonCode"> Reason: <span><%=Html.DropDownListFor(model => model.ReasonCode, new SelectList(Model.LookupCodes["C_EXCPT_RSN"], "Key", "Value", (null != Model.ReasonCode) ? Model.ReasonCode.Trim() : Model.ReasonCode))%></span> </label> <label>Action Taken:<span><%=Html.DropDownListFor(model => model.ActionCode, new SelectList(Model.LookupCodes["C_EXCPT_ACT"], "Key", "Value", (null != Model.ActionCode) ? Model.ActionCode.Trim() : Model.ActionCode))%></span></label> <label>&nbsp;</label> </div> <div class="fiveper"> <label>Follow-Up:<span class="datepicker-container"><input type="text" id="exc-flwup-<%=Model.ExceptionID %>" name="exc-flwup-<%=Model.ExceptionID %>" value="<%=Model.FollowupDate %>" /></span></label> <label>Inqurity #: <span><%=Html.EditorFor(model => model.IOL)%></span> </label> <label>&nbsp;</label> <label>Comment: <span> <%=Html.TextAreaFor(model => model.Comment, new { })%> <%=Html.ValidationMessageFor(model => model.Comment)%> </span> </label> </div> <div id="hide" style="display:none"> <label><span><%=Model.Sequence %></span></label> <label><span><%=Model.AssignedId %></span></label> <span id="gui-stat-<%=Model.ExceptionID%>"> <%=Model.LookupCodes["C_EXCPT_STAT"].FirstOrDefault(model => model.Key.Trim().Equals(Model.ExceptionStatus.Trim())).Value%></span> <span>Last Updated:</span> <%=Model.LastUpdateUser.StartsWith("ATPB") ? "SYSTEM" : Model.LastUpdateUser%><br /> <%=Model.LastUpdated%> <% if (DateTime.Now.Date == Model.LastUpdated.Value .Date ) {%> <%=Math.Round((DateTime.Now - (DateTime)Model.LastUpdated).TotalHours, 0)%> hr<%} %> <p> <%=Html.EditorFor(model => model.SequenceDateTimeAsString)%> <%=Html.EditorFor(model => model.AssignedId)%> <span><%=Html.EditorFor(model => model.Origination)%></span> </p> </div> </fieldset> <script type="text/javascript"> $(document).ready(function() { function validate_excpt(formData, jqForm, options) { var form = jqForm[0]; } // post-submit callback function showResponse(responseText, statusText, xhr, $form) { if (responseText.substring(0, 16) != "System.Exception") { $('#error-msg-<%=Model.ExceptionID %> span:last').html('<strong>Update successful.</strong>'); } else { $('#error-msg-<%=Model.ExceptionID %> span:last').html('<strong>Update failed.</strong> ' + responseText.substring(0, 48)); } $('#error-msg-<%=Model.ExceptionID %>').removeClass('hide'); $('#gui-stat-<%=Model.ExceptionID %>').html(responseText[1]); } $('#exc-<%=Model.ExceptionID %>').ajaxForm({ target: '#error-msg-<%=Model.ExceptionID %>', beforeSubmit: validate_excpt, success: showResponse, dataType: 'json' }).enable(<%=Model.EnableEdit.ToString().ToLower() %>); $("input[id^='exc-flwup-']").datepicker({ duration: 0, buttonImage: '/Content/images/calender.gif', buttonImageOnly: true, showOn:'button', constrainInput: true, showTime: true, stepMinutes: 30, stepHours: 1, altTimeField: '', time24h: true, minDate: 0 }); $("input[id^='exc-flwup-<%=Model.ExceptionID%>']").click(function() { $(this).val(''); }); $('#ui-timepicker-div').bgiframe(); }); </script> Using this code I am disabling the fields when the view loads.. like this my view displyas for number of users which I am going to selct using this below code I am able to disable only first Fiedset not for other fieldsets? $("#Fieldset1").find("input, select,textarea").attr('disabled', 'disabled'); why its happening? I need to disable for how many users I select.... thanks..

    Read the article

  • What is the best practice for adding persistence to an MVC model?

    - by etheros
    I'm in the process of implementing an ultra-light MVC framework in PHP. It seems to be a common opinion that the loading of data from a database, file etc. should be independent of the Model, and I agree. What I'm unsure of is the best way to link this "data layer" into MVC. Datastore interacts with Model //controller public function update() { $model = $this->loadModel('foo'); $data = $this->loadDataStore('foo', $model); $data->loadBar(9); //loads data and populates Model $model->setBar('bar'); $data->save(); //reads data from Model and saves } Controller mediates between Model and Datastore Seems a bit verbose and requires the model to know that a datastore exists. //controller public function update() { $model = $this->loadModel('foo'); $data = $this->loadDataStore('foo'); $model->setDataStore($data); $model->getDataStore->loadBar(9); //loads data and populates Model $model->setBar('bar'); $model->getDataStore->save(); //reads data from Model and saves } Datastore extends Model What happens if we want to save a Model extending a database datastore to a flatfile datastore? //controller public function update() { $model = $this->loadHybrid('foo'); //get_class == Datastore_Database $model->loadBar(9); //loads data and populates $model->setBar('bar'); $model->save(); //saves } Model extends datastore This allows for Model portability, but it seems wrong to extend like this. Further, the datastore cannot make use of any of the Model's methods. //controller extends model public function update() { $model = $this->loadHybrid('foo'); //get_class == Model $model->loadBar(9); //loads data and populates $model->setBar('bar'); $model->save(); //saves } EDIT: Model communicates with DAO //model public function __construct($dao) { $this->dao = $dao; } //model public function setBar($bar) { //a bunch of business logic goes here $this->dao->setBar($bar); } //controller public function update() { $model = $this->loadModel('foo'); $model->setBar('baz'); $model->save(); } Any input on the "best" option - or alternative - is most appreciated.

    Read the article

  • Importing Multiple Schemas to a Model in Oracle SQL Developer Data Modeler

    - by thatjeffsmith
    Your physical data model might stretch across multiple Oracle schemas. Or maybe you just want a single diagram containing tables, views, etc. spanning more than a single user in the database. The process for importing a data dictionary is the same, regardless if you want to suck in objects from one schema, or many schemas. Let’s take a quick look at how to get started with a data dictionary import. I’m using Oracle SQL Developer in this example. The process is nearly identical in Oracle SQL Developer Data Modeler – the only difference being you’ll use the ‘File’ menu to get started versus the ‘File – Data Modeler’ menu in SQL Developer. Remember, the functionality is exactly the same whether you use SQL Developer or SQL Developer Data Modeler when it comes to the data modeling features – you’ll just have a cleaner user interface in SQL Developer Data Modeler. Importing a Data Dictionary to a Model You’ll want to open or create your model first. You can import objects to an existing or new model. The easiest way to get started is to simply open the ‘Browser’ under the View menu. The Browser allows you to navigate your open designs/models You’ll see an ‘Untitled_1′ model by default. I’ve renamed mine to ‘hr_sh_scott_demo.’ Now go back to the File menu, and expand the ‘Data Modeler’ section, and select ‘Import – Data Dictionary.’ This is a fancy way of saying, ‘suck objects out of the database into my model’ Connect! If you haven’t already defined a connection to the database you want to reverse engineer, you’ll need to do that now. I’m going to assume you already have that connection – so select it, and hit the ‘Next’ button. Select the Schema(s) to be imported Select one or more schemas you want to import The schemas selected on this page of the wizard will dictate the lists of tables, views, synonyms, and everything else you can choose from in the next wizard step to import. For brevity, I have selected ALL tables, views, and synonyms from 3 different schemas: HR SCOTT SH Once I hit the ‘Finish’ button in the wizard, SQL Developer will interrogate the database and add the objects to our model. The Big Model and the 3 Little Models I can now see ALL of the objects I just imported in the ‘hr_sh_scott_demo’ relational model in my design tree, and in my relational diagram. Quick Tip: Oracle SQL Developer calls what most folks think of as a ‘Physical Model’ the ‘Relational Model.’ Same difference, mostly. In SQL Developer, a Physical model allows you to define partitioning schemes, advanced storage parameters, and add your PL/SQL code. You can have multiple physical models per relational models. For example I might have a 4 Node RAC in Production that uses partitioning, but in test/dev, only have a single instance with no partitioning. I can have models for both of those physical implementations. The list of tables in my relational model Wouldn’t it be nice if I could segregate the objects based on their schema? Good news, you can! And it’s done by default Several of you might already know where I’m going with this – SUBVIEWS. You can easily create a ‘SubView’ by selecting one or more objects in your model or diagram and add them to a new SubView. SubViews are just mini-models. They contain a subset of objects from the main model. This is very handy when you want to break your model into smaller, more digestible parts. The model information is identical across the model and subviews, so you don’t have to worry about making a change in one place and not having it propagate across your design. SubViews can be used as filters when you create reports and exports as well. So instead of generating a PDF for everything, just show me what’s in my ‘ABC’ subview. But, I don’t want to do any work! Remember, I’m really lazy. More good news – it’s already done by default! The schemas are automatically used to create default SubViews Auto-Navigate to the Object in the Diagram In the subview tree node, right-click on the object you want to navigate to. You can ask to be taken to the main model view or to the SubView location. If you haven’t already opened the SubView in the diagram, it will be automatically opened for you. The SubView diagram only contains the objects from that SubView Your SubView might still be pretty big, many dozens of objects, so don’t forget about the ‘Navigator‘ either! In summary, use the ‘Import’ feature to add existing database objects to your model. If you import from multiple schemas, take advantage of the default schema based SubViews to help you manage your models! Sometimes less is more!

    Read the article

  • Backbone Model fetched from Lithium controller is not loaded properly in bb Model

    - by Nilesh Kale
    I'm using backbone.js and Lithium. I'm fetching a model from the server by passing in a _id that is received as a hidden parameter on the page. The database MongoDB has stored the data correctly and can be viewed from console as: { "_id" : ObjectId("50bb82694fbe3de417000001"), "holiday_name" : "SHREE15", "description": "", "star_rating" : "3", "holiday_type" : "family", "rooms" : "1", "adults" : "2", "child" :"0", "emails" : "" } The Lithium Model class is so: class Holidays extends \lithium\data\Model { public $validates = array( 'holiday_name' => array( array( 'notEmpty', 'required' => true, 'message' => 'Please key-in a holiday name! (eg. Family trip for summer holidays)' ))); } The backbone Holiday model is so: window.app.IHoliday = Backbone.Model.extend({ urlRoot: HOLIDAY_URL, idAttribute: "_id", id: "_id", // Default attributes for the holiday. defaults: { }, // Ensure that each todo created has `title`. initialize: function(props) { }, The code for backbone/fetch is: var Holiday = new window.app.IHoliday({ _id: holiday_id }); Holiday.fetch( { success: function(){ alert('Holiday fetched:' + JSON.stringify(Holiday)); console.log('HOLIDAY Fetched: \n' + JSON.stringify(Holiday)); console.log('Holiday name:' + Holiday.get('holiday_name')); } } ); Lithium Controller Code is: public function load($holiday_id) { $Holiday = Holidays::find($holiday_id); return compact('Holiday'); } PROBLEM: The output of the backbone model fetched from server is as below and the Holiday model is not correctly 'formed' when data returns into backbone Model: HOLIDAY Fetched: {"_id":"50bb82694fbe3de417000001","Holiday":{"_id":"50bb82694fbe3de417000001","holiday_name":"SHREE15","description":"","star_rating":"3","holiday_type":"family","rooms":"1","adults":"2","child":"0","emails":""}} iplann...view.js (line 68) Holiday name:undefined Clearly there is some issue when the data is passed/translated from Lithium and loaded up as a model into backbone Holiday model. Is there something very obviously wrong in my code?

    Read the article

  • Custom Model Binding of IEnumerable Properties in ASP.Net MVC 2

    - by Doug Lampe
    MVC 2 provides a GREAT feature for dealing with enumerable types.  Let's say you have an object with a parent/child relationship and you want to allow users to modify multiple children at the same time.  You can simply use the following syntax for any indexed enumerables (arrays, generic lists, etc.) and then your values will bind to your enumerable model properties. 1: <% using (Html.BeginForm("TestModelParameter", "Home")) 2: { %> 3: < table > 4: < tr >< th >ID</th><th>Name</th><th>Description</th></tr> 5: <% for (int i = 0; i < Model.Items.Count; i++) 6: { %> 7: < tr > 8: < td > 9: <%= i %> 10: </ td > 11: < td > 12: <%= Html.TextBoxFor(m => m.Items[i].Name) %> 13: </ td > 14: < td > 15: <%= Model.Items[i].Description %> 16: </ td > 17: </ tr > 18: <% } %> 19: </ table > 20: < input type ="submit" /> 21: <% } %> Then just update your model either by passing it into your action method as a parameter or explicitly with UpdateModel/TryUpdateModel. 1: public ActionResult TestTryUpdate() 2: { 3: ContainerModel model = new ContainerModel(); 4: TryUpdateModel(model); 5:   6: return View("Test", model); 7: } 8:   9: public ActionResult TestModelParameter(ContainerModel model) 10: { 11: return View("Test", model); 12: } Simple right?  Well, not quite.  The problem is the DefaultModelBinder and how it sets properties.  In this case our model has a property that is a generic list (Items).  The first bad thing the model binder does is create a new instance of the list.  This can be fixed by making the property truly read-only by removing the set accessor.  However this won't help because this behaviour continues.  As the model binder iterates through the items to "set" their values, it creates new instances of them as well.  This means you lose any information not passed via the UI to your controller so in the examplel above the "Description" property would be blank for each item after the form posts. One solution for this is custom model binding.  I have put together a solution which allows you to retain the structure of your modelModel binding is a somewhat advanced concept so you may need to do some additional research to really understand what is going on here, but the code is fairly simple.  First we will create a binder for the parent object which will retain the state of the parent as well as some information on which children have already been bound. 1: public class ContainerModelBinder : DefaultModelBinder 2: { 3: /// <summary> 4: /// Gets an instance of the model to be used to bind child objects. 5: /// </summary> 6: public ContainerModel Model { get; private set; } 7:   8: /// <summary> 9: /// Gets a list which will be used to track which items have been bound. 10: /// </summary> 11: public List<ItemModel> BoundItems { get; private set; } 12:   13: public ContainerModelBinder() 14: { 15: BoundItems = new List<ItemModel>(); 16: } 17:   18: protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 19: { 20: // Set the Model property so child binders can find children. 21: Model = base.CreateModel(controllerContext, bindingContext, modelType) as ContainerModel; 22:   23: return Model; 24: } 25: } Next we will create the child binder and have it point to the parent binder to get instances of the child objects.  Note that this only works if there is only one property of type ItemModel in the parent class since the property to find the item in the parent is hard coded. 1: public class ItemModelBinder : DefaultModelBinder 2: { 3: /// <summary> 4: /// Gets the parent binder so we can find objects in the parent's collection 5: /// </summary> 6: public ContainerModelBinder ParentBinder { get; private set; } 7: 8: public ItemModelBinder(ContainerModelBinder containerModelBinder) 9: { 10: ParentBinder = containerModelBinder; 11: } 12:   13: protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 14: { 15: // Find the item in the parent collection and add it to the bound items list. 16: ItemModel item = ParentBinder.Model.Items.FirstOrDefault(i => !ParentBinder.BoundItems.Contains(i)); 17: ParentBinder.BoundItems.Add(item); 18: 19: return item; 20: } 21: } Finally, we will register these binders in Global.asax.cs so they will be used to bind the classes. 1: protected void Application_Start() 2: { 3: AreaRegistration.RegisterAllAreas(); 4:   5: ContainerModelBinder containerModelBinder = new ContainerModelBinder(); 6: ModelBinders.Binders.Add(typeof(ContainerModel), containerModelBinder); 7: ModelBinders.Binders.Add(typeof(ItemModel), new ItemModelBinder(containerModelBinder)); 8:   9: RegisterRoutes(RouteTable.Routes); 10: } I'm sure some of my fellow geeks will comment that this could be done more efficiently by simply rewriting some of the methods of the default model binder to get the same desired behavior.  I like my method shown here because it extends the binder class instead of modifying it so it minimizes the potential for unforseen problems. In a future post (if I ever get around to it) I will explore creating a generic version of these binders.

    Read the article

  • Should a model binder populate all of the model?

    - by Richard
    Should a model binder populate all of the model, or only the bits that are being posted? For example, I am adding a product in my system and on the form i want the user to select which sites the new product will appear on. Therefore, in my model I want to populate a collection called "AllAvailableSites" to render the checkboxes for the user to choose from. I also need to populate the model with any chosen sites on a post in case the form does not validate, and I need to represent the form showing the initial selections. It would seem that I should let the model binder set the chosen sites on the model, and (once in the controller method) I set the "AllAvailableSites" on the model. Does that sound right? It seems more efficient to set everything in the model binder but someone is suggesting it is not quite right. I am grateful for any advice; I have to say that all the MVC model binding help online seems to cite really simple examples, nothing complicated. Do I really need a GET and a POST version of a method? Can't they just take the same view model? Then I check in my model binder if it is a GET/POST, and populate all the model accordingly.

    Read the article

  • How to create a link to Nintex Start Workflow Page in the document set home page

    - by ybbest
    In this blog post, I’d like to show you how to create a link to start Nintex Workflow Page in the document set home page. 1. Firstly, you need to upload the latest version of jQuery to the style library of your team site. 2. Then, upload a text file to the style library for writing your own html and JavaScript 3. In the document set home page, insert a new content editor web part and link the text file you just upload. 4. Update the text file with the following content, you can download this file here. <script type="text/javascript" src="/Style%20Library/jquery-1.9.0.min.js"></script> <script type="text/javascript" src="/_layouts/sp.js"></script> <script type="text/javascript"> $(document).ready(function() { listItemId=getParameterByName("ID"); setTheWorkflowLink("YBBESTDocumentLibrary"); }); function buildWorkflowLink(webRelativeUrl,listId,itemId) { var workflowLink =webRelativeUrl+"_layouts/NintexWorkflow/StartWorkflow.aspx?list="+listId+"&ID="+itemId+"&WorkflowName=Start Approval"; return workflowLink; } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if(results == null){ return ""; } else{ return decodeURIComponent(results[1].replace(/\+/g, " ")); } } function setTheWorkflowLink(listName) { var SPContext = new SP.ClientContext.get_current(); web = SPContext.get_web(); list = web.get_lists().getByTitle(listName); SPContext.load(web,"ServerRelativeUrl"); SPContext.load(list, 'Title', 'Id'); SPContext.executeQueryAsync(setTheWorkflowLink_Success, setTheWorkflowLink_Fail); } function setTheWorkflowLink_Success(sender, args) { var listId = list.get_id(); var listTitle = list.get_title(); var webRelativeUrl = web.get_serverRelativeUrl(); var startWorkflowLink=buildWorkflowLink(webRelativeUrl,listId,listItemId) $("a#submitLink").attr('href',startWorkflowLink); } function setTheWorkflowLink_Fail(sender, args) { alert("There is a problem setting up the submit exam approval link"); } </script> <a href="" target="_blank" id="submitLink"><span style="font-size:14pt">Start the approval process.</span></a> 5. Save your changes and go to the document set Item, you will see the link is on the home page now. Notes: 1. You can create a link to start the workflow using the following build dynamic string configuration: {Common:WebUrl}/_layouts/NintexWorkflow/StartWorkflow.aspx?list={Common:ListID}&ID={ItemProperty:ID}&WorkflowName=workflowname. With this link you will still need to click the start button, this is standard SharePoint behaviour and cannot be altered. References: http://connect.nintex.com/forums/27143/ShowThread.aspx How to use html and JavaScript in Content Editor web part in SharePoint2010

    Read the article

  • Class-Level Model Validation with EF Code First and ASP.NET MVC 3

    - by ScottGu
    Earlier this week the data team released the CTP5 build of the new Entity Framework Code-First library.  In my blog post a few days ago I talked about a few of the improvements introduced with the new CTP5 build.  Automatic support for enforcing DataAnnotation validation attributes on models was one of the improvements I discussed.  It provides a pretty easy way to enable property-level validation logic within your model layer. You can apply validation attributes like [Required], [Range], and [RegularExpression] – all of which are built-into .NET 4 – to your model classes in order to enforce that the model properties are valid before they are persisted to a database.  You can also create your own custom validation attributes (like this cool [CreditCard] validator) and have them be automatically enforced by EF Code First as well.  This provides a really easy way to validate property values on your models.  I showed some code samples of this in action in my previous post. Class-Level Model Validation using IValidatableObject DataAnnotation attributes provides an easy way to validate individual property values on your model classes.  Several people have asked - “Does EF Code First also support a way to implement class-level validation methods on model objects, for validation rules than need to span multiple property values?”  It does – and one easy way you can enable this is by implementing the IValidatableObject interface on your model classes. IValidatableObject.Validate() Method Below is an example of using the IValidatableObject interface (which is built-into .NET 4 within the System.ComponentModel.DataAnnotations namespace) to implement two custom validation rules on a Product model class.  The two rules ensure that: New units can’t be ordered if the Product is in a discontinued state New units can’t be ordered if there are already more than 100 units in stock We will enforce these business rules by implementing the IValidatableObject interface on our Product class, and by implementing its Validate() method like so: The IValidatableObject.Validate() method can apply validation rules that span across multiple properties, and can yield back multiple validation errors. Each ValidationResult returned can supply both an error message as well as an optional list of property names that caused the violation (which is useful when displaying error messages within UI). Automatic Validation Enforcement EF Code-First (starting with CTP5) now automatically invokes the Validate() method when a model object that implements the IValidatableObject interface is saved.  You do not need to write any code to cause this to happen – this support is now enabled by default. This new support means that the below code – which violates one of our above business rules – will automatically throw an exception (and abort the transaction) when we call the “SaveChanges()” method on our Northwind DbContext: In addition to reactively handling validation exceptions, EF Code First also allows you to proactively check for validation errors.  Starting with CTP5, you can call the “GetValidationErrors()” method on the DbContext base class to retrieve a list of validation errors within the model objects you are working with.  GetValidationErrors() will return a list of all validation errors – regardless of whether they are generated via DataAnnotation attributes or by an IValidatableObject.Validate() implementation.  Below is an example of proactively using the GetValidationErrors() method to check (and handle) errors before trying to call SaveChanges(): ASP.NET MVC 3 and IValidatableObject ASP.NET MVC 2 included support for automatically honoring and enforcing DataAnnotation attributes on model objects that are used with ASP.NET MVC’s model binding infrastructure.  ASP.NET MVC 3 goes further and also honors the IValidatableObject interface.  This combined support for model validation makes it easy to display appropriate error messages within forms when validation errors occur.  To see this in action, let’s consider a simple Create form that allows users to create a new Product: We can implement the above Create functionality using a ProductsController class that has two “Create” action methods like below: The first Create() method implements a version of the /Products/Create URL that handles HTTP-GET requests - and displays the HTML form to fill-out.  The second Create() method implements a version of the /Products/Create URL that handles HTTP-POST requests - and which takes the posted form data, ensures that is is valid, and if it is valid saves it in the database.  If there are validation issues it redisplays the form with the posted values.  The razor view template of our “Create” view (which renders the form) looks like below: One of the nice things about the above Controller + View implementation is that we did not write any validation logic within it.  The validation logic and business rules are instead implemented entirely within our model layer, and the ProductsController simply checks whether it is valid (by calling the ModelState.IsValid helper method) to determine whether to try and save the changes or redisplay the form with errors. The Html.ValidationMessageFor() helper method calls within our view simply display the error messages our Product model’s DataAnnotations and IValidatableObject.Validate() method returned.  We can see the above scenario in action by filling out invalid data within the form and attempting to submit it: Notice above how when we hit the “Create” button we got an error message.  This was because we ticked the “Discontinued” checkbox while also entering a value for the UnitsOnOrder (and so violated one of our business rules).  You might ask – how did ASP.NET MVC know to highlight and display the error message next to the UnitsOnOrder textbox?  It did this because ASP.NET MVC 3 now honors the IValidatableObject interface when performing model binding, and will retrieve the error messages from validation failures with it. The business rule within our Product model class indicated that the “UnitsOnOrder” property should be highlighted when the business rule we hit was violated: Our Html.ValidationMessageFor() helper method knew to display the business rule error message (next to the UnitsOnOrder edit box) because of the above property name hint we supplied: Keeping things DRY ASP.NET MVC and EF Code First enables you to keep your validation and business rules in one place (within your model layer), and avoid having it creep into your Controllers and Views.  Keeping the validation logic in the model layer helps ensure that you do not duplicate validation/business logic as you add more Controllers and Views to your application.  It allows you to quickly change your business rules/validation logic in one single place (within your model layer) – and have all controllers/views across your application immediately reflect it.  This help keep your application code clean and easily maintainable, and makes it much easier to evolve and update your application in the future. Summary EF Code First (starting with CTP5) now has built-in support for both DataAnnotations and the IValidatableObject interface.  This allows you to easily add validation and business rules to your models, and have EF automatically ensure that they are enforced anytime someone tries to persist changes of them to a database.  ASP.NET MVC 3 also now supports both DataAnnotations and IValidatableObject as well, which makes it even easier to use them with your EF Code First model layer – and then have the controllers/views within your web layer automatically honor and support them as well.  This makes it easy to build clean and highly maintainable applications. You don’t have to use DataAnnotations or IValidatableObject to perform your validation/business logic.  You can always roll your own custom validation architecture and/or use other more advanced validation frameworks/patterns if you want.  But for a lot of applications this built-in support will probably be sufficient – and provide a highly productive way to build solutions. 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

  • MVC 2 Entity Framework View Model Insert

    - by cannibalcorpse
    This is driving me crazy. Hopefully my question makes sense... I'm using MVC 2 and Entity Framework 1 and am trying to insert a new record with two navigation properties. I have a SQL table, Categories, that has a lookup table CategoryTypes and another self-referencing lookup CategoryParent. EF makes two nav properties on my Category model, one called Parent and another called CategoryType, both instances of their respective models. On my view that creates the new Category, I have two dropdowns, one for the CategoryType and another for the ParentCategory. When I try and insert the new Category WITHOUT the ParentCategory, which allows nulls, everything is fine. As soon as I add the ParentCategory, the insert fails, and oddly (or so I think) complains about the CategoryType in the form of this error: 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. When I step through, I can verifiy that both ID properties coming in on the action method parameter are correct. I can also verify that when I go to the db to get the CategoryType and ParentCategory with the ID's, the records are being pulled fine. Yet it fails on SaveChanges(). All that I can see is that my CategoryParent dropdownlistfor in my view, is somehow causing the insert to bomb. Please see my comments in my httpPost Create action method. My view model looks like this: public class EditModel { public Category MainCategory { get; set; } public IEnumerable<CategoryType> CategoryTypesList { get; set; } public IEnumerable<Category> ParentCategoriesList { get; set; } } My Create action methods look like this: // GET: /Categories/Create public ActionResult Create() { return View(new EditModel() { CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); } // POST: /Categories/Create [HttpPost] public ActionResult Create(Category mainCategory) { if (!ModelState.IsValid) return View(new EditModel() { MainCategory = mainCategory, CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); mainCategory.CategoryType = _db.CategoryTypeSet.First(ct => ct.Id == mainCategory.CategoryType.Id); // This db call DOES get the correct Category, but fails on _db.SaveChanges(). // Oddly the error is related to CategoryTypes and not Category. // Entities in 'DbEntities.CategorySet' participate in the 'FK_Categories_CategoryTypes' relationship. // 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. //mainCategory.Parent = _db.CategorySet.First(c => c.Id == mainCategory.Parent.Id); // If I just use the literal ID of the same Category, // AND comment out the CategoryParent dropdownlistfor in the view, all is fine. mainCategory.Parent = _db.CategorySet.First(c => c.Id == 2); _db.AddToCategorySet(mainCategory); _db.SaveChanges(); return RedirectToAction("Index"); } Here is my Create form on the view : <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div> <%= Html.LabelFor(model => model.MainCategory.Parent.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.Parent.Id, new SelectList(Model.ParentCategoriesList, "Id", "Name")) %> <%= Html.ValidationMessageFor(model => model.MainCategory.Parent.Id) %> </div> <div> <%= Html.LabelFor(model => model.MainCategory.CategoryType.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.CategoryType.Id, new SelectList(Model.CategoryTypesList, "Id", "Name"))%> <%= Html.ValidationMessageFor(model => model.MainCategory.CategoryType.Id)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Name) %> <%= Html.TextBoxFor(model => model.MainCategory.Name)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Name)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Description)%> <%= Html.TextAreaFor(model => model.MainCategory.Description)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Description)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.SeoName)%> <%= Html.TextBoxFor(model => model.MainCategory.SeoName, new { @class = "large" })%> <%= Html.ValidationMessageFor(model => model.MainCategory.SeoName)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.HasHomepage)%> <%= Html.CheckBoxFor(model => model.MainCategory.HasHomepage)%> <%= Html.ValidationMessageFor(model => model.MainCategory.HasHomepage)%> </div> <p><input type="submit" value="Create" /></p> </fieldset> <% } %> Maybe I've just been staying up too late playing with MVC 2? :) Please let me know if I'm not being clear enough.

    Read the article

  • Passing variables from Model to Model in codeigniter

    - by Craig Ward
    Hi, I need to pass a variable to model, that model needs to send another back and use that variable to query a different model. EG: I have a product_ID which I send to the product model, From that I find out the supplier_ID. I want to grab that supplier_ID to the supplier model to get the supplier name. How do you implement this in codeigniter?

    Read the article

  • JQuery pass model to controller

    - by slandau
    I want to pass the mvc page model back to my controller within a Javascript Object. How would I do that? var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/ExportToExcel")%>"; var jsonNickname = { model: Model, viewName: "<%= VirtualPathUtility.ToAbsolute("~/Views/Indications/TermSheetViews/Swap/CashFlows.aspx")%>", fileName: 'Cashflows.xls' } $.ajax({ type: "POST", url: urlString, data: jsonNickname, async: false, success: function (data) { $('#termSheetPrinted').append(data); } }); So where it says model: Model, I want the Model to be the actual page model that I declare at the top of the page: Inherits="System.Web.Mvc.ViewPage<Chatham.Web.Models.Indications.SwapModel>" How can I do that?

    Read the article

  • How should I architect my Model and Data Access layer objects in my website?

    - by Robin Winslow
    I've been tasked with designing Data layer for a website at work, and I am very interested in architecture of code for the best flexibility, maintainability and readability. I am generally acutely aware of the value in completely separating out my actual Models from the Data Access layer, so that the Models are completely naive when it comes to Data Access. And in this case it's particularly useful to do this as the Models may be built from the Database or may be built from a Soap web service. So it seems to me to make sense to have Factories in my data access layer which create Model objects. So here's what I have so far (in my made-up pseudocode): class DataAccess.ProductsFromXml extends DataAccess.ProductFactory {} class DataAccess.ProductsFromDatabase extends DataAccess.ProductFactory {} These then get used in the controller in a fashion similar to the following: var xmlProductCreator = DataAccess.ProductsFromXml(xmlDataProvider); var databaseProductCreator = DataAccess.ProductsFromXml(xmlDataProvider); // Returns array of Product model objects var XmlProducts = databaseProductCreator.Products(); // Returns array of Product model objects var DbProducts = xmlProductCreator.Products(); So my question is, is this a good structure for my Data Access layer? Is it a good idea to use a Factory for building my Model objects from the data? Do you think I've misunderstood something? And are there any general patterns I should read up on for how to write my data access objects to create my Model objects?

    Read the article

  • What is a good strategy for binding view objects to model objects in C++?

    - by B.J.
    Imagine I have a rich data model that is represented by a hierarchy of objects. I also have a view hierarchy with views that can extract required data from model objects and display the data (and allow the user to manipulate the data). Actually, there could be multiple view hierarchies that can represent and manipulate the model (e.g. an overview-detail view and a direct manipulation view). My current approach for this is for the controller layer to store a reference to the underlying model object in the View object. The view object can then get the current data from the model for display, and can send the model object messages to update the data. View objects are effectively observers of the model objects and the model objects broadcast notifications when properties change. This approach allows all the views to update simultaneously when any view changes the model. Implemented carefully, this all works. However, it does require a lot of work to ensure that no view or model objects hold any stale references to model objects. The user can delete model objects or sub-hierarchies of the model at any time. Ensuring that all the view objects that hold references to the model objects that have been deleted is time-consuming and difficult. It feels like the approach I have been taking is not especially clean; while I don't want to have to have explicit code in the controller layer for mediating the communication between the views and the model, it seems like there must be a better (implicit) approach for establishing bindings between the view and the model and between related model objects. In particular, I am looking for an approach (in C++) that understands two key points: There is a many to one relationship between view and model objects If the underlying model object is destroyed, all the dependent view objects must be cleaned up so that no stale references exist While shared_ptr and weak_ptr can be used to manage the lifetimes of the underlying model objects and allows for weak references from the view to the model, they don't provide for notification of the destruction of the underlying object (they do in the sense that the use of a stale weak_ptr allows for notification), but I need an approach that notifies the dependent objects that their weak reference is going away. Can anyone suggest a good strategy to manage this?

    Read the article

  • How do you formulate the Domain Model in Domain Driven Design properly (Bounded Contexts, Domains)?

    - by lko
    Say you have a few applications which deal with a few different Core Domains. The examples are made up and it's hard to put a real example with meaningful data together (concisely). In Domain Driven Design (DDD) when you start looking at Bounded Contexts and Domains/Sub Domains, it says that a Bounded Context is a "phase" in a lifecycle. An example of Context here would be within an ecommerce system. Although you could model this as a single system, it would also warrant splitting into separate Contexts. Each of these areas within the application have their own Ubiquitous Language, their own Model, and a way to talk to other Bounded Contexts to obtain the information they need. The Core, Sub, and Generic Domains are the area of expertise and can be numerous in complex applications. Say there is a long process dealing with an Entity for example a Book in a core domain. Now looking at the Bounded Contexts there can be a number of phases in the books life-cycle. Say outline, creation, correction, publish, sale phases. Now imagine a second core domain, perhaps a store domain. The publisher has its own branch of stores to sell books. The store can have a number of Bounded Contexts (life-cycle phases) for example a "Stock" or "Inventory" context. In the first domain there is probably a Book database table with basically just an ID to track the different book Entities in the different life-cycles. Now suppose you have 10+ supporting domains e.g. Users, Catalogs, Inventory, .. (hard to think of relevant examples). For example a DomainModel for the Book Outline phase, the Creation phase, Correction phase, Publish phase, Sale phase. Then for the Store core domain it probably has a number of life-cycle phases. public class BookId : Entity { public long Id { get; set; } } In the creation phase (Bounded Context) the book could be a simple class. public class Book : BookId { public string Title { get; set; } public List<string> Chapters { get; set; } //... } Whereas in the publish phase (Bounded Context) it would have all the text, release date etc. public class Book : BookId { public DateTime ReleaseDate { get; set; } //... } The immediate benefit I can see in separating by "life-cycle phase" is that it's a great way to separate business logic so there aren't mammoth all-encompassing Entities nor Domain Services. A problem I have is figuring out how to concretely define the rules to the physical layout of the Domain Model. A. Does the Domain Model get "modeled" so there are as many bounded contexts (separate projects etc.) as there are life-cycle phases across the core domains in a complex application? Edit: Answer to A. Yes, according to the answer by Alexey Zimarev there should be an entire "Domain" for each bounded context. B. Is the Domain Model typically arranged by Bounded Contexts (or Domains, or both)? Edit: Answer to B. Each Bounded Context should have its own complete "Domain" (Service/Entities/VO's/Repositories) C. Does it mean there can easily be 10's of "segregated" Domain Models and multiple projects can use it (the Entities/Value Objects)? Edit: Answer to C. There is a complete "Domain" for each Bounded Context and the Domain Model (Entity/VO layer/project) isn't "used" by the other Bounded Contexts directly, only via chosen paths (i.e. via Domain Events). The part that I am trying to figure out is how the Domain Model is actually implemented once you start to figure out your Bounded Contexts and Core/Sub Domains, particularly in complex applications. The goal is to establish the definitions which can help to separate Entities between the Bounded Contexts and Domains.

    Read the article

  • ASP.NET. MVC2. Entity Framework. Cannot pass primary key value back from view to [HttpPost]

    - by Paul Connolly
    I pass a ViewModel (which contains a "Person" object) from the "EditPerson" controller action into the view. When posted back from the view, the ActionResult receives all of the Person properties except the ID (which it says is zero instead of say its real integer) Can anyone tell me why? The controllers look like this: public ActionResult EditPerson(int personID) { var personToEdit = repository.GetPerson(personID); FormationViewModel vm = new FormationViewModel(); vm.Person = personToEdit; return View(vm); } [HttpPost] public ActionResult EditPerson(FormationViewModel model) <<Passes in all properties except ID { // Persistence code } The View looks like this: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Afp.Models.Formation.FormationViewModel>" %> <% using (Html.BeginForm()) {% <%= Html.ValidationSummary(true) % <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.Title) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.Title) %> <%= Html.ValidationMessageFor(model => model.Person.Title) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.Forename)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.Forename)%> <%= Html.ValidationMessageFor(model => model.Person.Forename)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.Surname)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.Surname)%> <%= Html.ValidationMessageFor(model => model.Person.Surname)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.DOB) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.DOB, String.Format("{0:g}", Model.DOB)) <%= Html.ValidationMessageFor(model => model.DOB) %> </div>--%> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.Nationality)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.Nationality)%> <%= Html.ValidationMessageFor(model => model.Person.Nationality)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.Occupation)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.Occupation)%> <%= Html.ValidationMessageFor(model => model.Person.Occupation)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.CountryOfResidence)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.CountryOfResidence)%> <%= Html.ValidationMessageFor(model => model.Person.CountryOfResidence)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.PreviousNameForename)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.PreviousNameForename)%> <%= Html.ValidationMessageFor(model => model.Person.PreviousNameForename)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.PreviousSurname)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.PreviousSurname)%> <%= Html.ValidationMessageFor(model => model.Person.PreviousSurname)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Person.Email)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Person.Email)%> <%= Html.ValidationMessageFor(model => model.Person.Email)%> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } % And the Person class looks like: [MetadataType(typeof(Person_Validation))] public partial class Person { public Person() { } } [Bind(Exclude = "ID")] public class Person_Validation { public int ID { get; private set; } public string Title { get; set; } public string Forename { get; set; } public string Surname { get; set; } public System.DateTime DOB { get; set; } public string Nationality { get; set; } public string Occupation { get; set; } public string CountryOfResidence { get; set; } public string PreviousNameForename { get; set; } public string PreviousSurname { get; set; } public string Email { get; set; } } And ViewModel: public class FormationViewModel { public Company Company { get; set; } public Address RegisteredAddress { get; set; } public Person Person { get; set; } public PersonType PersonType { get; set; } public int CurrentStep { get; set; } } }

    Read the article

  • LLBLGen Pro feature highlights: grouping model elements

    - by FransBouma
    (This post is part of a series of posts about features of the LLBLGen Pro system) When working with an entity model which has more than a few entities, it's often convenient to be able to group entities together if they belong to a semantic sub-model. For example, if your entity model has several entities which are about 'security', it would be practical to group them together under the 'security' moniker. This way, you could easily find them back, yet they can be left inside the complete entity model altogether so their relationships with entities outside the group are kept. In other situations your domain consists of semi-separate entity models which all target tables/views which are located in the same database. It then might be convenient to have a single project to manage the complete target database, yet have the entity models separate of each other and have them result in separate code bases. LLBLGen Pro can do both for you. This blog post will illustrate both situations. The feature is called group usage and is controllable through the project settings. This setting is supported on all supported O/R mapper frameworks. Situation one: grouping entities in a single model. This situation is common for entity models which are dense, so many relationships exist between all sub-models: you can't split them up easily into separate models (nor do you likely want to), however it's convenient to have them grouped together into groups inside the entity model at the project level. A typical example for this is the AdventureWorks example database for SQL Server. This database, which is a single catalog, has for each sub-group a schema, however most of these schemas are tightly connected with each other: adding all schemas together will give a model with entities which indirectly are related to all other entities. LLBLGen Pro's default setting for group usage is AsVisualGroupingMechanism which is what this situation is all about: we group the elements for visual purposes, it has no real meaning for the model nor the code generated. Let's reverse engineer AdventureWorks to an entity model. By default, LLBLGen Pro uses the target schema an element is in which is being reverse engineered, as the group it will be in. This is convenient if you already have categorized tables/views in schemas, like which is the case in AdventureWorks. Of course this can be switched off, or corrected on the fly. When reverse engineering, we'll walk through a wizard which will guide us with the selection of the elements which relational model data should be retrieved, which we can later on use to reverse engineer to an entity model. The first step after specifying which database server connect to is to select these elements. below we can see the AdventureWorks catalog as well as the different schemas it contains. We'll include all of them. After the wizard completes, we have all relational model data nicely in our catalog data, with schemas. So let's reverse engineer entities from the tables in these schemas. We select in the catalog explorer the schemas 'HumanResources', 'Person', 'Production', 'Purchasing' and 'Sales', then right-click one of them and from the context menu, we select Reverse engineer Tables to Entity Definitions.... This will bring up the dialog below. We check all checkboxes in one go by checking the checkbox at the top to mark them all to be added to the project. As you can see LLBLGen Pro has already filled in the group name based on the schema name, as this is the default and we didn't change the setting. If you want, you can select multiple rows at once and set the group name to something else using the controls on the dialog. We're fine with the group names chosen so we'll simply click Add to Project. This gives the following result:   (I collapsed the other groups to keep the picture small ;)). As you can see, the entities are now grouped. Just to see how dense this model is, I've expanded the relationships of Employee: As you can see, it has relationships with entities from three other groups than HumanResources. It's not doable to cut up this project into sub-models without duplicating the Employee entity in all those groups, so this model is better suited to be used as a single model resulting in a single code base, however it benefits greatly from having its entities grouped into separate groups at the project level, to make work done on the model easier. Now let's look at another situation, namely where we work with a single database while we want to have multiple models and for each model a separate code base. Situation two: grouping entities in separate models within the same project. To get rid of the entities to see the second situation in action, simply undo the reverse engineering action in the project. We still have the AdventureWorks relational model data in the catalog. To switch LLBLGen Pro to see each group in the project as a separate project, open the Project Settings, navigate to General and set Group usage to AsSeparateProjects. In the catalog explorer, select Person and Production, right-click them and select again Reverse engineer Tables to Entities.... Again check the checkbox at the top to mark all entities to be added and click Add to Project. We get two groups, as expected, however this time the groups are seen as separate projects. This means that the validation logic inside LLBLGen Pro will see it as an error if there's e.g. a relationship or an inheritance edge linking two groups together, as that would lead to a cyclic reference in the code bases. To see this variant of the grouping feature, seeing the groups as separate projects, in action, we'll generate code from the project with the two groups we just created: select from the main menu: Project -> Generate Source-code... (or press F7 ;)). In the dialog popping up, select the target .NET framework you want to use, the template preset, fill in a destination folder and click Start Generator (normal). This will start the code generator process. As expected the code generator has simply generated two code bases, one for Person and one for Production: The group name is used inside the namespace for the different elements. This allows you to add both code bases to a single solution and use them together in a different project without problems. Below is a snippet from the code file of a generated entity class. //... using System.Xml.Serialization; using AdventureWorks.Person; using AdventureWorks.Person.HelperClasses; using AdventureWorks.Person.FactoryClasses; using AdventureWorks.Person.RelationClasses; using SD.LLBLGen.Pro.ORMSupportClasses; namespace AdventureWorks.Person.EntityClasses { //... /// <summary>Entity class which represents the entity 'Address'.<br/><br/></summary> [Serializable] public partial class AddressEntity : CommonEntityBase //... The advantage of this is that you can have two code bases and work with them separately, yet have a single target database and maintain everything in a single location. If you decide to move to a single code base, you can do so with a change of one setting. It's also useful if you want to keep the groups as separate models (and code bases) yet want to add relationships to elements from another group using a copy of the entity: you can simply reverse engineer the target table to a new entity into a different group, effectively making a copy of the entity. As there's a single target database, changes made to that database are reflected in both models which makes maintenance easier than when you'd have a separate project for each group, with its own relational model data. Conclusion LLBLGen Pro offers a flexible way to work with entities in sub-models and control how the sub-models end up in the generated code.

    Read the article

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