We are trying to make food order and deliver web application with .NET MVC and razor view.
But we are having issue with using multiple models in same view page. We found some solutions for this problem but they didn't work very well with our implementations.
Basically, I am implementing restaurant owners' register system in Register.cshtml. In same view I also did registration for normal users. If check box for "restaurant owner" is checked, user must enter his restaurant informations and register it using same controller. So if checkbox is checked, i need to access to Restaurant model too.
-We tried using Tuple but it didn't work with foreach and MVC binding functions such as Html.DropDownList().
We also could try merging two model in one view model, but this looks so brute force way to do this and there will be too much code repeat if we use this approach for every dual model combinations we need.
Can you help us to find alternative ways to use 2 models in 1 view?
In simple words, you cannot access data from multiple models in your view since you specify something like this #model WebApplication88.Models.YourModel on top of each view. This view can refer data from this YourModel only.
But there is no limitation on what model/list of models you can refer to on top of each view. So add a new class YourViewModel populate it all required data you want to access in the view and pass it to the view from the controller.
Read this article for more info Multiple Models in Single View in MVC.
Also refer this code project article on handling multiple models in a single view.
First of all you can't have more than one model for view because it is against all point of MVC. So you have two options:
ViewModel: Create a view model based on your mix of user and restaurant models with all properties together.
add a restaurant object to your user model and populate when user is restaurant owner else keep it null.
Related
I have this view called BlogsCategory.cshtml that belongs to CategoryController. Currently on this view the page loads a list of my Blog Categories the way its supposed to.
In addition to that data loading already I want to be able to also load data on that same view(BlogsCategory.cshtml) that belongs to another Controller called AdvertisementController whos data comes from another table called tblAdvertisement.
I did not want to create a database relationship between the BlogCategories Table and the Advertisement Table so I was wondering how in the world can I accomplish this via partial views that can load data from AdvertisementController on a view that belongs to CategoryController.
I have tried to add this #Html.Partial on that view but keep getting an error that states that the error below.
#model List<Systex.Models.tblCategory>
#Html.Partial("~/Views/Advertisement/Horizontal1.cshtml")
System.InvalidOperationException: 'The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Systex.Models.tblBlogsCategory]', but this dictionary requires a model item of type 'Systex.Models.tblAdvertisement'.'
Then the view that holds the piece of data that I want to load looks like this. This is a view of the AdvertisemenController that I am trying to call from the BlogsCategory.cshtml view.
Horizontal1.cshtml
#model Systex.Models.tblAdvertisement
//Display these 2 strings on the view called BlogsCategory.cshtml
#Model.BlogCategoriesListVerticalString1
#Model.BlogCategoriesListVerticalString2
If you dont want to create a DB relationship, which if you are using EFCore I would recommend, then you will have to pass some identifying information to the controller such as an ID and look up the data then to map to the view model.
I have a model called Course and another model called SelectedCourse. These two models represent two different tables and have exclusive properties to their own and hence not the same type.
I would like to display List<Course> on my page in the form of multiple check-boxes. The courses that are available in the List<SelectedCourse> should be marked as checked.
How do I build my ViewModel to achieve this?
For Post, I would like to return the list of my ViewModel back to the controller and the POST action. And then be able to only delete/add the items that were modified (selected/un-selected) to the table representing List<SelectedCourse>.
How do I achieve this?
(Because I don't know how to create my ViewModel, I cannot provide cshtml or controller actions to prove effort)
Your ViewModel could contain a list of e.g. CourseViewModel objects, which contains the properties of the Course you are using in the view, but also a bool for representing whether the course is selected. See this question for an example.
Your action method (POST) could take the list of CourseViewModels as argument, which allows the form to post that list of ViewModels back to the controller. See this question for an example.
Well I have a group controller and view in the project, in which the model binding is GroupViewModel. But the group page is complex, and users will be able to make discussion topics. On this group view page, I have forms that allow users to post topics/replies. The model used for these forms can be TopicViewModel or ReplyViewModel, but the original model binding is only for GroupViewModel. It is declared at the beginning of the cshtml page:
#model MyProject.ViewModels.GroupBrowseViewModel
So I wonder, is it possible to have forms bind to different view model from the one declared at the top? If so, how to achieve this?
Model binding really has nothing to do with the model used in your razor view. At least not technically.
The first thing you have to understand is that there is no magic here. This is straight HTTP posted values, and if you don't understand how HTTP posting works, I suggest you read up on it. It's just a series of name/value pairs.
When you post, the routing framework looks at the selected action method, and the parameters that method takes, then it creates new instances of those parameters, and tries to match them up with similarly named values from the posted values.
So, in other words, there is no direct connection here between the model you use on the page, and the model used in the posted controller action. It's all based on naming convention. This naming convention is "helped" by the model you declare on the page, and the Html helpers create form fields with names that match up to model entries so that the model binder can figure these out more easily.
So, what this means is that in order to post to a different action, with a different model, all you need are fields in your form that have the names that the new model expects.
This can be done in a number of ways, from defining those fields manually, to using Partial view in which you pass an instance of the model you intend to post to as the model parameter.
You can use 2 partial views in the same view, and switch from the controller which one to show.
Or you can make a new ViewModel and this view model will contain references to both of your views, and in the view html based on your logic your can switch reading from any child ViewModel.
I have read a few other stackoverflow posts regarding dashboard setup in a view, but I am still struggling a bit. I have one master query that is returning a detailed view of my data, since I only want to hit the database once. So I have a Controller Action called GetEmployeeInfo() that returns a IEnumerable<EmployeeBase> model class. I want to be able to take this class and break it apart into different divs in a view. For example, I would have three divs on top of the View aggregating row count by employee category and 2 divs on the botton that shows the detailed table. Can this be accomplished strictly through one view by setting up conditional/aggregate statements all over or do I use partial views or something else. Or is using one controller action a problem?
Thank you.
I used the answer from Pat Burke (see comments under my question. I posted it below as well). I created one base class and one partial view for my employee categories that has all the properties I needed. I did the same for my detail portion. Then I created the DashboardViewModel which had 3 IEnumerable<EmployeeCategoryBase> properties as well as 2 IEnumerable<EmployeeDetailInfo> properties. Then I created a strongly typed DashboardViewModel view with 5 divs that used #{Html.RenderPartial(ViewName,model.property);}
Another alternative is to have your Dashboard view strongly typed to a View Model like "DashboardViewModel" which is composed of different collections which correspond to the data needed for each sub-part. This would also put the aggregation logic to the server-side rather than on the client in JS. You could even have partial views included, each of which corresponds to a sub-part and a collection of data in your View Model. It's good practice to have your view model directly correlate to the data needed by your view
MVC3 has entity framework that makes create, delete, edit methods within a controller.
I am making a control panel that allows to edit multiple tables. How do I incorporate a controller(the entity framework) within another controller(the control panel)?
Any clever work around?
For example http://example.com/Control_panel/Another_Controller
Ok for this, there are two ways lets say you have a default controlpanel action in your ControlPanel controller, you can have a variable that comes in and says what you are trying to control, lets call it controlID, you can then use RedirectToAction to go to that action instead, like this
public ActionResult controlPanel(object controlId){
if(controlId.equals(something)){
RedirectToAction(SomeAction, SomeController);
}
}
The other one is you can use the same idea and call the controller action directly. Like this:
var result= new SomeController().SomeAction();
Although this is breaking MVC design as you should have it be a more universal function rather than a controller, as controllers are designed to control datamovement between Models and Views. If I see some of the code I can give you a more specific response.
If you want to edit data from multiple tables from the same page, you accomplish this by use of view models. The data you present to the user in your view does not need to have a 1:1 relationship with a table or a model for that matter.
A view model will allow you to pick data from various sources, present the same to the user for viewing or editing and if the user saves the same, you can pick the view model from your controller action and use that data to update one or more tables.