asp.net mvc custom modelbinder - how to perfom updates with assosciated entities - asp.net-mvc

I am trying to understand how associated entities are updated when using custom modelbinders.
If you have a Product entity with a relationship to a Category entity and you are displaying a list of category choice for a product in a dropdown on a form.
The the user assigns a new category and that change needs to be persisted with the Product. How is the binding implemented to assign the updated category? The properties f the Product are easy enough, but how do you set the Product.Category = category?
Hope that is clear :-)

Sounds like your custom model binding is there, you're just trying to setup up your relationship between your Product and Category.
To do this you would do something like this:
product.CategoryReference.EntityKey =
new EntityKey("Context.Category", "ID", categoryID);
That will simply update the foreign key relationship in your entity.

Related

Generate dropdown with scaffolding in MVC View

i am new in mvc and just reading a article from this link http://weblogs.asp.net/scottgu/ef-code-first-and-data-scaffolding-with-the-asp-net-mvc-3-tools-update
view the below image there is two model class one is product and one is category and category class has one property called Products which return ICollection
and when generate UI with scaffolding pointing to product model class then UI generate with product details and a dropdown appear for category.
i just do not understand how scaffolding incorporate a drodown for category when generate a UI page for product. product has no link for category but how category related drodown comes in product page. just help me to understand it. thanks
here are few screen shot
i just like to know when we generate product view page using scaffolding then we point our product model class and product model class has no property for category then why and how category related drop down appear in product view page. if u know the reason then share the concept in detail. thanks

MVC with View Model - Create an object optionally

I use MVC with View Models (I create separate View Model for each View).
I have 2 objects; Product and Category; Product can have a category.
I have separate view models (productCreateVM, CategoryCreateVM)
I can create product or category;and user can choose one of current categories while creating a new product, no problem.
What I need to do is that ; users can choose one of current categories or create a new category than choose it, while creating a new product.
If I add CategoryCreateVM in ProductCreateVM, then CategoryCreateVM's mandatory fields need to be filled in, in order the model state to be valid.
but if user already found a category for their product and didnt create a new one; I can not fill all the mandatory fields of CategoryCreateVM.
On the other hand; if user is creating a new category from product create view; then all the validations should be applied (category name lenght etc).
Any suggestions how to approach to this?
If you want to use more complex validations see if http://foolproof.codeplex.com/ will be sufficient.
It it should provide you with the conditional validation you need
You should consider rendering the Create Category View as a partial view within the Create Product View.
Its visibility can be toggled by e.g. the selection of Create Category within a Category drop-down menu.
For example:
#Html.Partial("Category/Create")

Concept on displaying cross-table(conjunction) data in ASP MVC

Just a rookie in .NET MVC world and still learning
I created three EF models in framework, one is clients, one is order, and items, below is the relation:
Client Order Items
PK:ID PK Order.id PK Items.ID
... FK:Client.id ...
FK:Item.id
In this case I wanna display all the client information and the item details they've bought in one table, obviously I cannot use any DBcontext here. So what should I do to combine the three table's info and output that? Create a new model on those three?
Any ideas or article are very welcomed!
I would create a ViewModel with all of the Data that you want to display. This is the model that will get populated in the controller and then it would get passed to the View.
So in the View it would use the ViewModel and wouldn't need to know about the underlying Database Model.
And in the Controller you would get the data needed and populate the ViewModel and pass that model onto the View.
Here is a page with an examples. There are plenty more out there too. http://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html

EF4 + Poco = Problem Updating many to many relationships

Let me explain the whole context:
I'm using ASP.NET MVC 2, EF4 (POCO).
I trying to do a generic repository for my app.
I'm having problem on updating a many to many relationship.
I have an item that is related to other by a many to many table. In the View, the user picks the desired Categories, and send just the chosen id's to the Controller.
Then, the Controller queries the Category Repository, adding it to the main item:
item.Categories.Add(CategoriesRepository.Single(id);
But, when I go the Repository and try to save like this:
Entities.ApplyCurrentValues(entity);
Context.SaveChanges();
But, the state of my entity is Added.
Then, I Cannot save my entity :(.
How can I solve this problem?
Thanks for your answers.
I have in the View, the following code:
<%= Html.CheckBoxList("Categories", ((IEnumerable<Categories>)ViewData["Categories"]).ToDictionary(c => c.ID.ToString(), c => c.Name)
, Model.Categories.ToDictionary(c => c.ID.ToString(),c => c.Name )) %>
Where CheckBoxList is a HTMLHelper.
Im putting the ids as values in the View, because I dont know other way to put and then get this information from the View.
How can I use the ObjectStateManager.ChangeRelationshipState method?
Like this? :
itemRepository.Db.ObjectStateManager.ChangeRelationshipState(item, item.Categories, "Categories", System.Data.EntityState.Modified);
I trying in this way, but it returns error.
Help! lol
You've got a few problems.
1) ApplyCurrentValues only works for scalar-properties. Since your trying to add a Category to the Categories navigational property on Item, this will not work.
2) You say this:
the user picks the desired Categories, and send just the chosen id's to the Controller.
How can your Controller accept a bunch of id's? How is this model binding done? We need more info on how your View is bound to your model, what's being passed to the action method. But it sounds like you need to redesign this particular View with the help of a ViewModel.
3) Change tracking with POCO's in MVC is a royal pain in the butt. In your scenario, you'll need to use ObjectStateManager.ChangeRelationshipState to manually set the Categories relationship to **Modified.
Honesty though, it's more pain than it's worth. I went through this same problem.
Cop it on the chin - go grab the entity first and use Controller.UpdateModel:
[HttpPost]
public ActionResult Item(Item item)
{
// get the existing item
var existingItem = ItemRepository.Single(item.Id);
// use MVC to update the model, including navigational properties
UpdateModel(existingItem);
// save changes.
Context.SaveChanges();
}

Using a dynamic list of checkboxes in a view, how to create the model

I have an asp mvc 2 app lication where I want to display a list of check boxes that a user can select, based on a list of records in a database. To display the list my model contains a List object and the view has a foreach, and outputs Html.CheckBox for each item in the list.
Is there a way to get the model populated with the selected checkboxes, given that the model can't have specific properties for each checkbox, because the list is dynamic? Or do I have to manually iterate through the forms variables myself?
Edit: Extra details as per sabanito's comment
So in a simple view/model scenario, if my model had a property called Property1, then my view outputted a Textbox for Property1, when the form is posted via a submit button, the mvc framework will automatically populate a model with Property1 containing the text that was entered into the textbox and pass that model to the Controllers action.
Because I am dealing with a dynamic list of options the user could check, I can't write explicit boolean properties in my model and explicitly create the checkboxes in my view. Given that my list is dynamic, I'm wondering if there are ways to create my model and view so that the mvc framework is able to populate the model correctly when the form is posted.
Here's what I would do:
Are you having any issues generating the checkbox's dynamically?
If not, create a property on your ViewModel that is a:
public List<string> CheckboxResults { get; set; }
When you generate your checkbox's in the view make sure they all share the name = "CheckboxResults". When MVC see's your ViewModel as a parameter on the action method it will automatically bind and put all the "CheckboxResults" results in the List (as well as your other ViewModel properties). Now you have a dynamic List based on which checkbox's your user checked that you can send to your DomainModel or wherever.
Pretty cool stuff. Let me know if you're having issues generating the checkbox's dynamically, that's kind of a seperate issue than model binding to a list.
Use a ViewModel that reflects your view exactly, and map your domain model(s) to the viewmodel.
At first it often seems appropriate to use domain models directly in the view, for no better reason than that they're simple to use. However, as the view gets more complex over time, you end up putting a TON of conditional logic in your view, and end up with spaghetti. To alleviate this, we typically create a ViewModel that correlates 1:1 with the view.

Resources