I have just started using MVC 2 , I have got a couple of queries , may be you guys can help me to clear my confusion.
Why mvc doesnt allows to inherit multiple models on a view page.
For instance if i inherited account model in my view , why i cant excess the associated entity properties with the account model in that view, We are only allowed to use the properties of that model like <%: Model.FirstName :%> Where First name is the property of account model. Why we cannot use <%:Model.account.aspnet_users.vehicle.make %> Where aspnet_users is associated with account through a foreign key vice versa. MVC 2 only allows <%:Model.account.aspnet_users.vehicle %> Therfore I cant use the associated property of vehicle which in this case is vehicle.make. I was thinking of doing something like <%: Html.TextboxFor(model => model.account.aspnet_users.vehicle.make %>.
ASP.NET MVC doesn't restrict navigation to related properties. If you cannot access the property it means either:
The relation is not loaded (it is null) and lazy loading is turned off / context is disposed
The relation is actually a collection an you must use Linq to navigate in the collection
Related
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
I have a view that is using a model
Inherits="System.Web.Mvc.ViewPage<Program.Models.Test>"
I am displaying data in the view using:
> <%= this.Model.Item == null ? "" :
> Html.GetString(this.Model.Item.Name) %>
Now I am trying to display a different item from another model on the same view, I thought ViewBag might help, so in my controler, I added:
ViewBag.GuideLines = ctx.GuideLines;
My question is can I display a specific item value from Guidelines model on the same view?
Thanks in advance.
I thought ViewBag might help
Wrong thought. ViewBag/ViewData never helps. I never use those 2 in any ASP.NET MVC application.
Now I am trying to display a different item from another model on the same view
Simply add this other model as property of the main view model. So you will have Model.Guidelines in the view.
in general if you need to use one or more of your domain models for use in a single page, you would create a viewmodel, basically a POCO that would contain just the properties from your domain objects (or any other information) that your view would need to be aware of. you would then strongly ype your view to this new viewmodel type and access the properties as per normal.
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();
}
I have two different user controls both of which has a textbox with the ID: txtEmail. When I render both controls in MVC, I'm running into conflicting IDs. Does anyone have any suggestions to resolve this issue?
Yeah what I generally do is preface the id with the model name.
So my model might be MyModel so my id would be MyModel.txtEmail.
Unsure why you have txtEmail though in MVC. Generally you would have a textbox like so;
Html.TextBox("email") where email is the name of the field in your model.
I would place a small snip of code in the controller that will assign a dynamic name based on which control its coming from.
What griegs said except that if you have strongly typed your view to use a model with Email in you can use <%: Html.TextBoxFor(model => model.Email) %>. It will prefix the ID for you with the model name and everything will generally rock. You will need MVC2 though
User have to populate multistep questionnaire web-forms and step messages depend on the option chosen by user at the very beginning. Messages are stored in web.config file. I use asp.net mvc project, strong typed views and keep business logic separated from controller in static class. I don't want to make business logic dependency on web.config.
Well, I have to insert message into view that depends on session value.
There are at least 2 options how to implement this:
View model has property that is populated in controller/businessLogic and rendered in view like <%: Model.HelpMessage1 %>. I have to pass web.config values from controller to businessLogic that makes business logic methods signature too complex.
Create static helper class that is called from view like <%: ViewHelper.HelpMessage1(Model.OptionChosenAtTheVeryBeginning) %>. But in this case logic what to show seems to be separated into two classes: business logic & viewHelper.
What will you suggest?
Thank you in advance!
As Adrian pointed out, your problem belongs in the business domain. Why not get the message, and put it into a view model along with your other data/models.
It appears that deciding which messages have to be displayed and / or how models are assembled from these messages is part of your business logic. How about storing the messages in your business layer and let your business layer generate the model with populated messages?