ViewData, ViewBag and TempData violates MVC? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
If we all look at the mvc diagram, the view shouldn't know the models the controller gives out to (according to msdn mvc overview https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx). To me, the ViewData, ViewBag, and TempData violates this and I have been scratching my head at why these three concepts was introduced.
Maybe I am getting it wrong? I can easily pass data to the view using the models instead of these three.
Would like to know other people's opinion.
If you down vote please comment why.
thank you

I can easily pass data to the view using the models instead of these
three.
Yes definitely you can and in such case your view becomes a strongly typed view and you can see starting of your view has a line
#Model entityName
What if you don't want (for some reason) your view to be strongly typed at all. How do you think in such case you are going to pass the data to view.
That's the purpose of ViewData or ViewBaG or TempData.
the view shouldn't know the models the controller gives out to
I think you misinterpreted this line which can't be agreed upon. If your view needs data to be displayed in controls (may be an edit view), then from where it's going to get the data if it doesn't know from where to read the data.
View someway or other way must know the model data (either in form of directly passing the Model object or using any of those 3 technique).
EDIT:
Per your last comment:
can i not use this?
public class TestModel
{
public dynamic testproperty { get; set; }
}
Yes, probably you can but that's not a proper way. Try creating a strongly typed view with model as TestModel and use any scaffold template and see if scaffolding can generate a proper template.
It will not, since scaffolding internally uses reflection to go through your model properties and accordingly generate controls for those properties/members. Since you have a dynamic property, it will not be able to reflect that property. change the type to a static type like String and see it will generate a #Html.DisplayFor(modelItem => item.testproperty). That's the issue.
Even if you don't use any scaffolding template and generate controls by your hand; what type of control will you generate for your property? since it's tped as dynamic it could be anything (string, int, datetime, email...).
ViewBag or ViewData are state management technique to pass on small amount of data b/w the views or controller to views. You should always pass your data as Model object to your view as correctly stated by #SteveHarris.
Hope this makes t clear to some sense.

Related

Advice needed on c#MVC/EF modelling strategies [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 days ago.
Improve this question
Context:
I am writing a web application using SQL server database, C# MVC API layer, Next (React) front end. The database is already created and populated and is in full Third Normal Form (3NF) and the base entity classes have been autogenerated from the database, so using a database-first modelling approach. This will seem like a bit of a rant, but I want to know if I am approacing this correctly because it feels like an awful lot of boiler plate code but this may just be because my project is not big enough to reap the benefits.
These aren't my tables but the relationship is the same; namely 1:many relationships with a primary key of ParentTable.id and foreign key of ChildTable.ParentTable_id
Consider a system with 4 tables: Store, Customer, Order, OrderLine. Each customer belongs to only one store and each order belongs to only 1 customer. The base models have their respective links (1 Parent => N Children) and Inverse Link (1 Child => 1 Parent). When you call the .../api/store it doesn't contain any customers by default. If you modify the controller
_context.Stores.Include("Customers").ToListAsync()
This throws an error when returning it as JSON because of the cyclic link so I need to create ViewModels for both the Customer (exluding the Stores model, but just keeping the storeID) and for the Store (including the collection of CustomerViewModel). This is fine while this is the only VM I need for customer or store but what if I also need a customer view model that includes the orders, or a viewmodel for the marketing team and a different one for the finance team. What options do I have? I am thinking either different model names within the same namespace
StoreCustomerViewModel
FinanceCustomerViewModel
MarketingCustomerViewModel
or using namespaces
using ...models.finance -> CustomerViewModel
using ...models.marketing -> CustomerViewModel
Or am I thinking about this the wrong way? If I need to combine models (e.g. where the main model contains a collection of other models - Customer.orders = List-OrdersViewModel) can these cut across namespaces and if so how and what are the caveats around that.
I'm not sure but once I stumbled upon a similar problem (Eager Loading).
Some advised to use [JsonIgnore] above the properties I don't want.
others advised to add UseLazyLoading() in my program.cs
But what really worked for me was creating DTOs and using AutoMapper.
So try out each option and see what works for your project.

How does having multiple DataContexts work? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am building an application that has several tabs within the MainWindow view, each containing a couple DataGrids and varying bits of data. I've been researching all week on how to set the DataContext to multiple tables/objects/queries. The only answer I can seem to find from a couple different sources is to create a ViewModel container like so:
class VMContainer
{
public ViewModel1 VM1 {get; set;}
public ViewModel2 VM2 {get; set;}
}
However, I'm unable to find anything that further explains what this is doing. From my perspective, it doesn't seem like there's ever a point where the call for data is being made. Even further, I cannot fathom how to create a call that returns all of the datasets that I need into one object. Can anyone explain how this work or direct me to an article that explains having multiple sets of data as the datacontext of a view?
Edit : How do I return a dataset of datasets?
Thanks.
With a tab control, normally you would see a separate view for each tab's content, and each view would have an accompanying view-model.
A view-model provides the view with the data/properties it needs to display via data binding.
A single view-model can provide many different sets of data. When you mention a dataset, most likely this would be represented in the view-model as a ObservableCollection<T> property.
Here's a simple example of one of those properties using an MVVM framework that implements the INotifyPropertyChanged interface.
private ObservableCollection<MyDataType> myDataSet1;
public ObservableCollection<MyDataType> MyDataSet1
{
get => myDataSet1;
set => SetProperty(ref myDataSet1, value);
}
A view-model can provide many of these properties to the view.
When the view-model is instantiated you would have code that would do the data access and get the data from the database, and you would expose it through your properties so that the view can data bind to them.

Is it good approach to store all ViewModels in a CoreViewModel in order to provide communication between each other? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is it good approach to store all ViewModels in a CoreViewModel in order to provide communication between each other? Or better using MVVM Light framework or something similar? (I want to have no-argument constructors)
public void SetView(Type view)
{
foreach (ViewBase openView in OpenViews)
if (openView.GetType().Equals(view))
{
currentView = openView;
currentView.Reset();
return;
}
currentView = Activator.CreateInstance(view) as ViewBase;
OpenViews.Add(currentView);
}
Ed Plunkett suggests an approach I use, but I'll try to elaborate.
If I have an application that has several sub-controls (say a control per tab page in a tab control) that I want to use then the MainWindow view will bind to the main view's view model in XAML:
<Window.DataContext>
<MainWindowViewModel/>
</Window.DataContext>
The MainWindowViewModel will declare the sub-view models as public properties and in the constructor instantiate and assign a view model object to the property.
Then it is a simple question of binding the data context of a sub-control on to the relevant view model property of the MainWindowViewModel.
<Control DataContext="{Binding ExampleControlViewModel}"/>
Then if a sub-control further breaks down into smaller components, it will declare its own view model properties and the sub-views or sub-controls will bind appropriately. Thus creating a hierarchy of view models that parallel the structure in your view/control hierarchy.
Since the whole tree of view models are initiated from the MainViewModel then it is possible to use Dependency Injection to pass down objects down through the hierarchy. For example, a mediator object to allow messaging between view models or a common database access service class.
If your application opens and closes sub-windows it gets more complicated. How to do that in an MVVM way is beyond the scope of my reply. What is relevant is that you can instantiate a view programatically and inject the view model with something like this:
(new ExampleWindow() { DataContext = new ExampleWindowViewModel(_mediator) }).ShowDialog();
Where _mediator is the object I'm using for message passing between view models.

How to Update database from UI which has many textboxes and CheckBox in asp.net and SQL Server? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am new to ASP.net. I have a webform where I have 40 text box 18 drop downs and 29 checkbox. I need to load the all data from these controls to SQL server database table using stored procedure. I dont want to pass all the parameters one by one and update the table.
Is there any other short way to do it? Please help
I am not sure I follow your question here?
The simplest way, would be to do a model object. Create a method that accepts the model object that includes all the data from your form. This methods feeds the stored procedure call.
This is the common way to do it. And the fastest. You need to assign the data to data-fields. There is no way around it really. But of course it can be done in many different ways.
So you want a more specific answer, you will have to elaborate what you mean by:
"I dont want to pass all the parameters one by one and update the
table."
I can't come up with a scenario where it would be desireable to pass each parameter one by one into an update statement...
but you will have to mention each field in your SQL stored procedure, that you want to update.
if that is your only question:
UPDATE table-name
SET column-name = value, column-name = value, ...
WHERE condition
If you have used a model in your view and used Razor syntax to render the relevant controls than if you have a form defined, posting back to the controller that accepts the same model as it's parameter will handle the binding of all the properties back to the model.
You then either parse the model or use the properties and send them down to entity framework, or any other ORM that you might be using, and have it handle the update operation.
[HttpPost]
public ActionResult YourPostMethod(YourModelUsedInView model)
{
// process your model here and send it down to the DB.
}

In MVVM pattern what is the recommended order of instantiation? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I got this asked in an interview recently . He wanted to know the order of instantiation of Model View and ViewModel what the precise order of instantiation would be ?
I thought the view is always instantiated first and then comes the viewmodel and then comes the model. was i wrong ??
I thought the view is always instantiated first and then comes the viewmodel and then comes the model. was i wrong ??
There is no single standard. There are, in general, two approaches:
View-First - The View will be instantiated first, and in turn instantiate the ViewModel, which will likely create the underlying model. This typically means the order of instantiation is View->ViewModel->Model.
ViewModel-First - The ViewModel is created, which in turn instantiates the Model. The View is generated by the system based on DataTemplates after the ViewModel. This would mean the order of instantiation would be ViewModel->Model, then View (indirectly from XAML).
Most frameworks which are geared heavily towards a designer-first approach tend to do View-First construction. This makes it easier to work with the designer (in general).
Many frameworks which are geared heavily towards developer-focused scenarios will often do ViewModel first. This approach can actually lead to even less coupling, and simpler "code-only" construction of everything from the ViewModel level.
This is an open ended question because you can look at it conceptually, in which case it follows the acronym. If you look at it in practice (particularly referring to WPF or WinStore Apps) its a bit different.
Conceptually
Model should be instantiated first because all ensuing decisions of the application will be based on the model on which the app was designed to operate on. Then the view model, because views depend on view models, not the other way around. One VM can have multiple views, but one view generally does not have multiple view models (generally!). Then the view(s) that present the data.
Practice (In WPF and WinStore Apps)
The App class is instantiated first, which fits in some odd portion of the VM-M area. But that's not completely relevant because it's outside the scope of the pattern. The View is usually created and attached to the visual tree first. Then the ViewModel is instantiated in the code-behind, at which point the model is loaded. Then a massive UI refresh occurs that displays everything that was loaded initially. From then on out, everything in the 'conceptually' portion holds true.
This question may get closed due to opinions, as there is no definite answer. but this is what I've seen, read, and experienced.
Well that's a strange interview question. In my opinion and in general, I would agree with you. The view model would instantiate the model and the view would come first, instantiating the view model. But of course, it very much depends on the architecture of the application. The beauty of WPF enables these things to be done in different ways. Then you also have dependency injection, so I would say that the answer should really be 'it depends'.
The question is a bit silly, because it's limited to a simple scenario where each layer is a single class. Suppose one view model provides another one. If we decide "view comes first", do we need to create another view before we are allowed to call that function on the original view model? What if the view must be chosen based on the returned view model? And on the flip side, if we decide "viewmodel comes first", what if the new viewmodel must be chosen based on parameters input from the view?
A layered architecture is about dependencies. MVVM says V depends on VM and VM depends M. It doesn't say anything about instantiation order. You might decide that dependencies should be passed into constructors, meaning that instantiation order needs to be M-VM-V, but I don't see any practical reason to try to enforce such a small detail throughout an entire application
IMHO it is a Trojan horse question to see how one thinks more than an actual answer to see if one can quantify their experience with actual MVVM projects.

Categories