MVC :: How To Update A Collection Of Objects In A View Model
Sep 14, 2010
I have been trying to design a form, which uses a view model that contains an object array. I want to set up this form so that when the submit button is clicked, all the members of the array are updated. Here is my code:
The class definition of the array element:
[Code]....
The problem is that when I clicked the submit button, none of the luSubject objects in the array Subjects got updated. But if I set up some initial values for the members of the luSubject objects, for instance, set the Name field to be "Maths" in the constructor of luSubject class, then it got displayed on the text box when the form page was loaded. This suggests that this form could display the data in the array, but cannot update it.
I'm trying to pass a list of items from a LINQ query to a View, but I'm having trouble figuring out how to resolve a type issue. Here's the error:
The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Project.Models.Diagnostic]' but this dictionary requires a model item of type 'Project.Models.Diagnostic'.
The issue seems to originate with this code from my Controller:
[Code]....
I tried changing the IQueryable<Diagnostic> to var and got the same error. Also played around with something like:
[Code]....
But then VS2008 says that diagnostics could never be null, and that's may not the best (or even valid) way to do it.
What I'm trying to do is rather basic, but I might have my facts mixed up. I have a details page that has a custom class as it's Model. The custom class uses 2 custom objects with yet another custom object a property of one of the 2. The details page outputs a fair amount of information, but allows the user to post a comment. When the user clicks the post button, the page gets posted to a Details action that looks something like this:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Details(VideoDetailModel vidAndComment) { ....} [Code]....
The only fields on the form that is posted are CommentText and VideoId. Here is what the VideoDetailModel looks like.
public class VideoDetailModel { public VideoDetailModel() { [Code].... I suppose if I added more form fields for the properties I need, they would get posted, but I only need 1 form entry field for the CommentText. If I could get the same Model objects value that were sent to the page to post with the page, it looks like the solution is rather simple. I think using the RenderPartial in the middle of a form is problematic somehow to how the form gets written in html. I can't really put my finger on why things went bonkers, but if I do my RenderPartials before my form and then begin my form with the text entry field and the hidden VideoId, the default ModelBinder works just fine. I was beginning the form, writing the hidden VideoId, rendering several partial views, create my CommentText field, and then closed the form out. The CommentText field would get bound just fine. The hidden VideoId would not. Maybe I missed a rule somewhere about using RenderPartial.
For completeness, the partial view I was rendering took a Comment object and just wrote out it's CommentText data. Several of these objects would exist for a single Video object. All of this data was in a custom type and passed into the View (the main view) as it's Model. This partial view did not have a form and did not have any data entry fields.
This is part of a larger problem which has plagued me for a while now (see "EntityCollection already initialized" error with entity as model in Asp.Net MVC? for the entire picture).
But I found a web site with someone who had faced a similar problem and apparently solved it for his needs [URL]. I tried it, but had to make some modifications to fit my code, and the helper methods supplied by a tutorial by Steven Sanderson (see previous post).
I'm very close it seems, but not quite:
UpdateModel(consultant, "Consultant"); if (vm.Programs != null) //Unnecessary? Can it even be null if it's initialized from the model? for (int i = 0; i < vm.Programs.Count; i++) { Program formProgram = vm.Programs[i]; Program modelProgram = consultant.Programs.SingleOrDefault(x => x.Id == formProgram.Id); if (modelProgram == null) _repository.AddProgram(formProgram); else modelProgram = formProgram; UpdateModel(modelProgram); //Doesn't work. The modelProgram object does get updated with the correct property values, but it isn't saved to the repository... } _repository.Save();
Although this follows the example on the site above, and the modelProgram does get updated with the changed properties, these values are not saved to the database on _repository.Save() on the Consultant object, even though the modelProgram object is a reference to a Program object on the Consultant... What am I doing wrong?
I am using the Entity Framework by the way, if it isn't clear.
(BTW, if anyone has any input on the previous question and the whole picture, that would be welcome too, it is still unresolved).
UPDATE: There was apparently a mistake in here: UpdateModel didn't actually do any updating, I had just referenced a different object (the one in the viewmodel) for the modelProgram, so of course it had the right property values. I still want ideas for how to achieve this though...
Note: I'm working with MVC3 RC and Razor views.I've got this model:
[Code]....
I want to have a strongly typed create view for this model, that allows you to insert 1 to many addresses and phone numbers as part of the view. Ideally, the Action is strongly typed as well:
[Code]....
What would this view look like to facilitate creating 1 to many Addresses and PhoneNumbers, as well as having the state re-created correctly if the ModelState fails when posting? I've tried a number of variations including EditorTemplates and can't figure out how to do this.
Using ASP.NET MVC 2, I have a model for a view. The view has a dropdownlist of roles that is populated by the model and there is a list below that of checkboxes with a number of privileges. I want to show only specific privileges depending on the dropdownlist selected roleID and have it update the privileges everytime the dropdownlist changes. I know how to do this in web forms ASP.net with absolutely no problem but I cannot seem to figure out where to start in ASP.NET MVC. Can someone please advise me what I need to do or towards a tutorial that will show me what to do? I am a novice in MVC.
public class ComponentType { public int ComponentTypeID { get; set; } public string Component_Type { get; set; } public string ComponentDesc { get; set; } } [code]...
I'm building an MVC 2 RTM app, and I want to be able to share my model across applications. I'd *like* to be able to implement it like:ASP.NET MVC2 app (holds Views and Controllers)Class library to hold Model(s)WCF app to handle the data transactions with the models via different data stores across apps I had the MVC app working fine, but I wanted to abstract the data stuff and be able to work with the model across apps through the WCF site, so I created a class library project and moved all of the Models classes into that and set-up a WCF app, then added project references to the MVC and WCF apps that point at the class library. The idea was I can create services that take and return objects from the model via method calls across apps. It appears that everything's wired up correctly in the MVC project, so I'm passing the objects stored in the Models class library between controllers and views and everythig is compiling just fine, but for some reason the data is not being passed back from the views to the controller on POST -- all of the properties in the classes are null or empty.
When I debug the app, I can see that the values are stored in the model data dictionary but not the model object itself. What am I doing wrong? Am I on the wrong path, or missing something obvious (to some)?
I am using ASP.net to retrieve data from a Lotus notes DB using OLEDB connection. I use a ADOrecordset to read the values. When I open the ADo connection, I would like to store each record being read in a custom object and thereby create a collection of custom objects as ADO connection times out when kept open for long.
I then need to iterate throught the collection of custom objects to retrieve the values.
I want to be able to update a model and all its collections of child objects in the same view. I have been referred to these examples: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ .
For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. In the view, the simple properties of the Consultant object is no problem, but the collection I cannot get a textbox to show up for. I tried following the examples in the links above, but it doesn't work. The problem is, in those examples the model is just a list (not an object with a child list property). And also, the model again is an EF model. And for some reason that doesn't seem to work as in those examples.
[Code]....
This stuff with the EditorTemplate works fine in Phil Haack's sample project, which I downloaded to try, but here, with the EF model or whatever the problem is, I don't get any textbox at all. The table in the view is just there as a test, because in the table I do get the rows for WorkExperiences, whether I add an empty WorkExperience object or fill out its properties doesn't matter, the rows show up for each object. But again, no textbox...
I'm new to linq. here is the scenario i need to write query for.I have a "Candidate" table with a varchar property "Skill"I have the table OR-mapped with LINQ to SQL on dbml file. Now I want to write linq query that:Selects all Candidates that have skill containing any of the keywords from ("asp.net","php","java")
I have an ASP.NET app with lots of textboxes all over the page that need updating at various points through program execution.
These textboxes actually belong to a certain class, so for easy updating I thought I could create a Dictionary(Of string, object) and add the control.ID and the control to it and then for updating do something like this:
(in case of updating textbox.text):
[code]....
However the text property of the textbox does not actually get updated. I'm mainly trying to avoid having to manually do textbox.text = somestring for each one of my textboxes every time I have to update them.
I am playing with Asp.net MVC 3, I was wondering how do you acheive a collection rendering in the view when the collection is made of 'real world' objects. Let's say I have a collection of client, each client may have an address and an adress may have a country.
When I write the following code it crashs if one of the client has a null address (or a null country). Object reference not set to an instance of an object.
I am binding a datalist to some table 0 of a dataset from the database. When I check the number of rows in the dataset table 0 it's coming as 129 but when I check the count of the datalist items(using Datalist_Name.Items.Count) inside the datalist item created event I am getting a maximum count of 128.Due, to this I am unable to assign values to the last label control(last as in the last row) present inside the datalist dynamically. I am not sure where I am going wrong. I even tried to replicate the same code inside the ItemDataBound event but even then I am getting the same error.
I need to bind a bunch of properties over my model entities. All of them uses the List<T> class. I already managed to write a model binder that can treat individualy types derived from that class, but i can't set the value of this property on the model. every time i check the model afer the bind process i see a list with 0 itens.
Here's how it runs.
After i post the values the model binder catchs up the types for bindingAt the custom model binder i check if this property is a List<T> typeIf it is then i perform the bind like it have to be, if not i let the default binder do the job.Finally i return the object binded. What happens next is the issue i've mentioned "i see a list with 0 itens" on the Model property.
I am asked to save and output a tournament bracket, like NCAA or US Open, two parties play and the winner move on to next round. To display the whole bracket, I need to find a way to maintain the hierarchy, say I have the following class:
[Code]....
This is good for a single contest inside the tournament, but how do I change the class or use other classes to support hierarchy? Also if possible can someone show me the best way to model this in SQL server tables?
i am creating a MVC2 application for pubs and bars. I have a model 'Opening_Time' with the following properties:
int Day,time OpeningTimetime ClosingTimeWhen adding/editing an Opening_Time, I want to validate an Opening_Time, to check the user isn't adding one for an existing Day (ie they can't have two entries for the same day).
How/Where is the best place to do this?
Preferably, I want to do it a Model level, so I can use Model.IsValid and the Html.Form helpers
I made a few changes to the DB in SQL server management studio then right clicked on the .edmx doc to get it to update. That seemed to work fine but when i compiled the app everything that referenced the EF seems to be broken.The Error list now contains the below error for all classes that used it.
The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?)
I have a view which takes two objects: booking and list of reasons for canceling that booking.I have two classes: clsBooking, clsBookingCancelationReason I can read both objects in my view - no problems there. After I read the objects, I display the booking details and I generate a list of cancelation reasons in the following way:
[Code]....
The code above generates a list of cancelation reasons.How do I pick up the selected ReasonId from the list? I need to generate a link that will contain the bookingId and the selected reason for canceling the booking.I can get the bookingId out easily since it's stored in the Model...but how do I go about the selected ReasonId?
I've been used to decorating data model classes with data annotation attributes, but the purist in me baulks slightly at including purely presentational attributes such as display format here. I am, however, quite happy to keep validation centric attributes here. One good reason I have to continue keeping all annotations etc. in the data model is that my view model aggregates data model classes, e.g.
my ViewModelBase.DetailItem<TEntity> property in the view model is just a reference to an entity class in my data model. If I wanted to move presentational annotations to the view model, I would have to quite radically revise my design to one where I duplicate data model properties in my view model and use an object mapping tool to populate view model objects based on data model objects.
Say I got a domain model as follows: (and my repository expect an instance of this object)
[Code]....
And a view model (which my views are based on)
[Code]....
At the moment I got it like this and have my controller action manually create a new Person object from the PersonModel object before passing it on to the repository, which does not feel right.
So I tried to have PersonModel inherit from Person and pass that to the repository (also tried casting the PersonModel to a Person object first), but that don't work out.
What's the right way to have PersonModel automatically cast to Person? I want to keep this logic as my current structure allow me to keep things really loosely coupled, with the repository layer not having a clue how it's being used.
I have an entity object as model input in my view. Not sure if it's the best approach, but I use the object references to get values from a related object.Let's say I've got a car entity and a manufacturer entity.Here's how it would look in my view
[Code]....
I've get a nullreferenceexception where the car entitity does not have a reference towards manufacturer. I'd like to output a " " if no manufacturer exists.
've created a Search partial view and it works, except for my view model. What i mean is, the partial view sends a string to my ActionResult Method, but only a string, that is not related to the view model that the partial view is built in. If i tell my ActionResult method to receive the view model in which the partial view is built in, it always tells me that i have null values. Here's my code This is my partial view:
[Code]....
Now here is my Model in my MoviesSearch view model: