c# mvc model vs viewbag - c#

Suppose you have a list of People A and a list of People B in a page. And these two are seperate classes in L2S, representing two different tables. Therefore, you cannot pass a single model as follows:
...
#model PeopleA
...
#foreach(var peopleA in Model.People) ...
#foreach(var peopleB in //what?)
Accordingly, I guess, I have three options to follow.
The first one is to devide the page into partial views so that I can pass a model through RenderAction helper. Since I will use these partial views only once this option does not seem attracting to me.
The second option would be to use ViewBags which I don't want to since I prefer strongly typed models.
The last one, finally, which I was about to use but wanted to ask before doing so, is to create a model as the following:
ModelMyPage.cs
public List<PeopleA> peopleA { get; set; }
public List<PeopleB> peopleB { get; set; }
MyController.cs
...
ModelMyPage m = new ModelMyPage();
m.peopleA = // query
m.peopleB = // another query
return(m);
And you got the idea. Is this the valid way to accomplish my task or is there a better c# way to do what I want?

Creating a ViewModel specific to the page, as your option 3 is the way I would do it.
I believe this is also the recommended approach.

No, there is not any better idea. In asp.net MVC, M stands for ViewModels, not the Business, Domain models. It is recommended to create ViewModels for your views and it's not reccomended to use Business Models. You should design your ViewModels to fit the need of controller interactions with Domain, and from controller to view interactions

Your first and third options seem both OK.
ad 1) "only using them once" is not a good argument-against. Use Partial views to organize views.
ad 2) Use the Viewbag to add small items like a lookup list.
ad 3) ViewModels are (becoming) common in MVC. This is probably the best approach.

I would do it the third way. Additionally, if you are going to render identical html for each person in both arrays, I would concat them before foreach:
var person in Model.PeopleA.Concat(Model.PeopleB)

I usually create a Model for the page, and name it as such, eg AccountDetailsPageModel. Then other models can be properies of this for complex pages.

Related

Returning multiples of the same model to view [duplicate]

I've been able to successfully return a model to a view and display the results in a strongly-typed fashion.
I have never seen an example where multiple models get returned. How do I go about that?
I suppose the controller would have something like this:
return View(lemondb.Messages.Where(p => p.user == tmp_username).ToList(), lemondb.Lemons.Where(p => p.acidity >= 2).ToList());
Does MVC let you return multiple models like that?
And then in the view I have this line at the top of the file:
#model IEnumerable<ElkDogTrader.Models.Message>
And I frequently make calls to "model" in the view.
#foreach (var item in Model)
If there were 2 models, how would I refer to them separately?
Is this possible with multiple models, or is this why people use ViewBag and ViewData?
You can create a custom model representing the data needed for your view.
public class UserView
{
public User User{get;set;}
public List<Messages> Messages{get;set;}
}
And then,
return View(new UserView(){ User = user, Messages = message});
In the view:
Model.User;
Model.Messages;
The ViewBag is useful because it is dynamically typed, so you can reference members in it directly without casting. You do, however, then lose static type checking at compile time.
ViewData can be useful if you have a one-off on your view data types and know the type and will be doing a cast in the view anyway. Some people like to keep the actual typed view pure in a sense that it represents the primary model only, others like to take advantage of the type checking at compile time and therefore make custom models needed for the view.
I believe ViewModel should be the way to go. Within the customary ViewModel, you can reference other models or define all the related domain models in the viewModel itself.

How create a complex EditorTemplate in ASP.NET MVC 5 with db query?

I would like to create a more complex EditorTemplate to select a customer from a list.
I'm aware of the DropDownListFor, but I would like to show cards with customer
pictures and some data not just a regular select list.
What I would like to do:
create an EditorTemplate for customer selecting, for instance... In any POCO Class
public class X{
[Key] int Id {get;set;}
[UIHint("CustomerSelector")] int Custumer_Id {get;set;}
}
And the "CustomerSelector" Editor template be able to query all clients and show them into a rich list.
What is the problem:
It's not a good idea to add querying logic from inside a view. This is against MVC pattern.
It's not very modular to query the customer list in every controller and pass it as argument to the EditorTemplate.
How can I create this EditorTemplate without mess up with the MVC pattern nor duplicate code in every controller?
Unfortunately, there is no truly good way to handle something like this. Your are correct that it's improper for database access to happen within a view. Not only does this violate MVC, but it would also require creating an additional instance of your context in the view, when you should really have just one per request.
The alternative, as you've mentioned, would be to do the query in the controller and then pass that into your view. Honestly, this is probably your best of bad options here.
Another choice I see is to use a child action. A child action allows you to confine the logic of querying the users and passing to a view in just one place. The downside is that that you would have to handle the field naming manually, because the rendering of the child actions view will be outside the scope of the form you're building. In other words, you'd have to do something like:
#Html.Action("CustomerSelect", new { fieldName = "Customer_Id" })
That's not really ideal, either, as now you've got a string that you've got to keep track of, and you'll have to be careful about actually providing the right name. For example, if this was a collection of items, then you'd actually need to pass something like "MyCollection[" + i.ToString() + "].Customer_Id". You can see that this starts to get messy quick. For this reason alone, I'd pretty much nix this as a possible solution.
One final option is to use an HtmlHelper extension. This has the same problem as an editor template would in that you're going to have to new up an instance of your context, but it's at least better in the respect that it's not being done inside a Razor view.

MVC creating multiple objects from single view

Just to make it clear, my question is how do you CREATE multiple objects using a single view. My ViewModel works fine, I can display multiple objects no problem.
Its been a while between .NET coding (last time I was coding in 2.0). I have created an MVC 4 project and successfully created a ViewModel (displaying data on a single view from multiple objects).
However, I cheated. I populated the database directly. I now face the question in reverse, what is the best practice for creating multiple objects from a single view?
In my example, I have a User, who has a userId. The userId is a foreign key in UserDetails.
Just trying to get back into the swing of it and wondering what you guys do?
There are 6 ways to pass multiple object in MVC
ViewModel
Partial View
ViewBag
ViewData
TempData
Tuple
Each one have there own pros and cons.you have to decide base on your issue in hand.
For more information you can refer code project article on it: How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
Let me give advantage and disadvantage of View Model
ViewModel :
Advantages
ViewModel allows us to render multiple model types in a View as a
single model.
Great intellisense support and compile time error checking on View
page.
ViewModel is good for security purpose also as Views have only what
they exactly need. Core domain models are not exposed to user.
If there is any change in core domain model, you do not need to
change anywhere in View code, just you need to modify corresponding
ViewModel.
Disadvantages
ViewModels add another layer between Models and Views so it increases
the complexity a little bit. So for small and demo applications, we
can use tuple or other ways to keep the things simple for demo.
Option 1:
The best approach is to use strongly typed views with Model or ViewModel.
For Example, you have two classes User and Education, you want to display all education details of user in a view, you can create a custom view model and pass it to view, where you view is strongly typed view model:
public class User
{
public int UserId {get;set;}
public string UserName {get;set}
-------
------
}
public class Education
{
public int UserId {get;set;}
public int DegreeId {get;set;}
public long Marks {get;set;}
---------------
--------------
}
Now create a view Model like this:
public class EducationViewModel
{
public User user {get;set;}
public List<Education> educationList {get;set;}
}
now pass the ViewModel to View and do this in View:
#model AppNameSpace.ViewModels.EducationViewModel
Tip: Create a folder named ViewModels and put all the viewmodel classes in it.
Option2:
Option 2 is to user ViewBag and pass multiple object from control to your view, ViewBag is accessible when you set some value in it in controller, you can access in the view of that action, after that it is automatically washed out, and its null if you access again it.
you can use ViewBag like this:
ViewBag.Message = "Using ViewBag";
and read value like this in View:
string Message = ViewBag.Message as string;
Option 3:
Option 3 is to store data in TempData, its once read only, means you set value in it, and when you read it, its automatically removed, TempData internally uses Session Variables.You can use TempData like this:
TempData["Key"] = "value";
now you read it in view:
string val = TempData["Key"] as string;
after reading it, it will be automatically removed, but you can keep it if you need it further like this:
TempData.Keep("Key");

send more than one model in MVC view if models are not related

How to send more than one model to the View from Controller?
This seems to be a question that is asked so many times, still there is no good answer for newbyes like me (I have not found it).
One sollution I have found is to create some "Parent" model and return collection of Parent child models. I do not want to create any parent model as both my models are not related to each other.
For example, I have two models that do not have relations between them, they are seperate models, for example, PersonModel and HardwareModel. I have two partials views, one needs PersonModel, another needs HardwareModel.
I have HomeController that returns View. This view displays both partial views. So I need to send PersonModel to _PersonPartialView. And I need to send HardwareModel to _HardwarePartialView.
How to do this?
I believe there should be an option to send Collection of unrelated models to View, but how exactly?
Edit:
Some explantions: we have complicated decisions, based on those we show one ore both partial views. You can think like dashboard. User can see one ore more "dashobard" like panels. So they could be even unrelated to each other. So the real situation is more complicated as we have more than 2 different models and different partialviews.
Maybe I should have absolutely different approach.
If the HomeView requires both PersonModel and HardwareModel, then those two combined are your model. So create eg
class HomeModel
{
PersonModel person;
HardwareModel hardware;
}
and you have your model.
Update
Based on the question update, if you have a dashboard-like page, then one option is to do away with the main view as you currently have it. Have a skeleton view, which defines the panel locations, but not their content. Then use AJAX calls to request partial views to populate the panels. That way, each partial view has its own model, separate from the others and you avoid having one view that need to know about all the models for all the partial views it might end up hosting.
We ended with putting abstract things that are part of several views, but not necessarily part of each model (e.g., cultures) into the ViewData / ViewBag. You can still access them in a strong-typed way by providing an extension method that encapsulates the view bag through a additional class. I'd suggest to put HardwareModel stuff into these, because it sounds like it's not the main thing on your web page.
public static HardwareSettings GetHardwareSettings (this HtmlHelper html)
{
// simplified; add lazy instantiation...
return (HardwareSettings) html.ViewData["hardware"];
}
This is for sure the best you can do. If this doesn't fit your problem, I suggest to reconsider your architecture, as it might be case that there are some flaws in it.
If this models is not linked, you should not return them from single controller method. If it should be showed on one page, you can load this partial views with ajax actions
one of examples how to do this click

Generic View Models?

I am wondering is it good practice to try to make a view that takes in a generic view model?
I am wondering this because someone mentioned that he was anticipating to have to do lots of duplicate code unless he started to make a generic view and generic view model.
So basically the views would be like just a set of controls. One view might have 2 controls(say a text-box and radio button) another view might have 50 controls on it.
They will all have the same look and feel(it just grows by number of controls) . Basically he was thinking having a view model takes in the object(domain object) looks at it and see's 50 fields and renders the right control types.
I guess a edit template could be used to figure out the controls however I am just not sold on a generic view model.
I like generics and they can do very powerful things and in some situations they are good but I am just not overall to crazy about them and try to not use.
I find most of the time it may reduce duplicate code but sometimes it makes the code alot more complicated. Of course this could just because I am still a relatively new to programming and it could be still above my skill level.
The next problem I have with it is I think that view models should be as flat as possible and only expose data that is actually going to be used so people don't start using properties that should never been in the view in the first place.
The next problem I have with it that it could just keep going if you have some complex object that has objects in it that has objects in it. It could go for a long long time.
Personally I avoid using generics in view models. I agree with most of the reasons you mentioned against them and particularly this one:
The next problem I have with it is I
think that view models should be as
flat as possible and only expose data
that is actually going to be used so
people don't start using properties
that should never been in the view in
the first place
The idea behind view models is that they need to be specifically tied to the requirements of a given view, not making them general (/generic) as your domain models are. I prefer duplicating code in view models compared to having some generic monster reused all over the views and partials.
And even in cases where you need to generate dynamic forms and controls you don't need to use generic view models.
So, unless you have some hyper specific scenario (can't think of any at the moment), it's probably a good thing to avoid generics in view models.
This being said, don't rule them out completely, if you feel that there is a situation in which generic view models could be useful don't hesitate to present it here, by explaining the scenario and showing all the code so that we can discuss it.
I don't see anything wrong with generic ViewModels. It is a good way to remove duplication and keep compile-time checks, as opposed to ViewBag.
Example:
Imagine you have a set of Model classes for Product, Category, etc.
Each class (ProductModel, CategoryModel) has an associated display and editor template, which generates appropriate view.
Now you want to construct a set of pages for view and edit.
I usually create a Layout (Master page in web forms) to render the common content (header, footer, menu, etc.)
Then I would create individual, strongly-typed views that accept as model ProductViewModel, CategoryViewModel, etc.
Now we need to define those view model classes. Each view model class should take an instance of ProductModel, CategoryModel, etc (which will be passed to the template). But the layout often requires some additional data (ie. selected menu, logged-in user name, etc). My solution is to create a generic ViewModel that encapsulates this duplicate data for the Layout:
public class EntityViewModel<T>
where T : EntityModel
{
public T Entity { get; set; }
public string UserName { get; set; }
public string SelectedMenu { get; set; }
}
Then you can easily create a ProductViewModel : EntityViewModel<ProductModel>, which contains everything the Layout need to render the page, and you can add there any additional, product-specific data.
As far as ViewModels go, I typically have all of my ViewModels inherit from a BaseViewModel that exposes methods that aid in implementing MVVM. If you'd like to see an example, just comment below.
I really do not like puting business logic inside viewmodel. I think that besides regular properties and error handling inside constructor nothing should be in view model. It makes much cleaner code, and you can more freely make additions to view model.
If you have to much duplicated code you can isolate it to separate viewmodel and then nest it where you need it.
This way you also have only what you need on your view.

Categories