Ajax Call in MVP asp.Net - asp.net

I am working on a small project with MVP implementation using Ajax, JQuery.
I implemented passive view MVP pattern and all presenters are connected from view by event handling.
The scenario is displaying a detail popup box from master list by clicking the link on master row.
I have to make an ajax call to display the detail list. Now my question is how can I make a call via Ajax from client side to invoke an event.
There are 2 scenarios in AJAX call that I know:
Call Page Method: In this, How can I call a page method (this is static by default) which internally invoke a event in presenter? If I call a presenter method directly in my view then It is violating the MVP pattern.
Call Web Service: How can I call a Web Service (Where it should be created?) how the presenter handle this service?
I googled so many sites but I couldn't find a right answer to implement.
Please clarify my questions and thanks for your support.
Thanks
Kalyan P

What I've done in an MVP framework I built was to use a web service, and that web service implements a presenter. So you call the web service, the web service fires an event to the presenter, the presenter responds to the model, and the web service returns anything within the model.
If I call a presenter method directly in my view then It is violating the MVP pattern.
It depends who you talk to; some are in favor of calling a method on the presenter, rather than using a view event (Jeremy Miller blogged about this, for one).

Related

Asp .NET Web API using MVVM pattern

I'm trying to understand how I should use the MVVM pattern for a CRUD operation. Currently I have methods in my API controller such as below. My question is: using MVVM pattern, should I still build my api like that (e.g., accessing DB)? Or should it be changed? If nothing changes, in which case I would implement ViewModels and how they should be managed by the API? I made some researches but it's still not clear for me.
public IHttpActionResult GetProduct(int id)
{
var product = _context.Products.SingleOrDefault(p => p.Id == id);
return Ok(product);
}
[HttpPost]
public IHttpActionResult CreateProduct(Product product)
{
...
_context.Products.Add(product);
_context.SaveChanges();
return Created(new Uri(Request.RequestUri + "/" + product.Id), product);
}
I think part of the problem is that you don't understand the role of MVVM in a web application. To understand, you have to look at a web application as composed of two separate applications--the server side, and the client side.
Server side, the pattern being used is MVC (not surprising, it's called ASP.NET MVC for a reason). If you're trying to fit your understanding of MVVM around the MVC pattern--don't. It doesn't apply. The MVC pattern on the server is simple to understand and implement; don't try to crowbar any MVVM into it. Just design your server side code using the server side pattern.
Client side is a different matter. By default, ASP.NET MVC using Razor pages renders your HTML on the server and delivers it for display to the client. And, typically, that HTML is designed to respond to users interaction with the page by posting back to the server. Your controller methods interpret these postbacks, perform the required logic, and render the correct razor page in response. But this isn't the only way to write a website.
More and more common, people are designing Single Page Applications. These use ajax callbacks to send the result of user actions back to the server, and then process the response. Server side, these requests are almost always handled through a WebApi controller method, not an ASP.NET MVC controller method. The request comes across the wire as ajax, and the result is usually returned as ajax. No HTML gets rendered. This is where MVVM comes into play.
Client side, these web pages typically use a javascript MVVM (ish) framework, like knockoutjs or angular. The response json is used to update view models that are bound to HTML elements in the web page. These frameworks handle synchronizing updates and user actions between the UI and these view models, just like Bindings synchronize updates between the UI and your view models in WPF.
Simply put, MVC is its own thing, and MVVM usually only exists within the client side of a website, and usually only when the website extensively uses ajax callbacks instead of postbacks.
And, to answer your direct question, if you're using MVVM on the client side, using ajax calls to perform your CRUD ops, you should design your WebApi controller methods to Post/Get/Put/Delete your data.
Personally, I always use the Repository Pattern for anything to do with CRUD operations, such as interacting with an entity in a database.
I would create a separate class called "ProductRepository" and put all the methods to Get, Create, Update, and Delete a Product in that class. This way, only your Respository cares about the details of interacting with the database and performing the CRUD operations on it. Your entire application should not care about how this gets done, only your Repository class. This is something known as the Single Reponsibility Principle. It is part of the "SOLID" principles of design and architecture.
Then, in either your Controller or ViewModel or where ever you need it to happen, you just have to instantiate the ProductRepository and use its methods throughout your application.
If you use a separate Web API for your service layer and data access layer, then you don't really need MVC. You just need a front-end framework to consume the Web API URLs, like AngularJS or any other JS framework of your choice.
If you want to use MVC, then you don't really need Web API. You can just build your service layer and data access layer into the MVC application, or build them as separate projects (class libraries) and include them in your overall project solution. It all just depends upon how you want the architecture to be and how complex you want to go with it.
But either way, a "ProductRepository" should be involved -- whether it is in your Web API (if you go that route), or in your MVC project (if you go that route). The ultimate goal is to have separation of concerns. You want to separate your business logic layer from your data access layer. You don't want to be making direct calls to the database throughout your entire application. That will result in code that is very tightly coupled and hard to test and maintain over time. If you ever change out databases in the future, you only want to update one place in the code, instead of many places.
Hope this helps you out some! Best regards and happy coding!!!

HTTPModule as ajax handler (IIS7+)

i have an argument at work about the best way to implement ajax handling for forms. we build all our forms under asp.net platform (sharepoint to be exact) but since we talk about public sites we though to cut the time-costing postbacks and make all postback in ajax request.
in order to best implement the server side i took a bit deeper look into handlers and modules and i then thought that i can cut all that by implementing a module that in his beginRequest identifies if its an ajax request (say by a special element in the querystring), and if so call CompleteRequest() and then in this module's endRequest if it was our ajax (say i flagged it in beginRequest) handle it.
so i would like to hear your thoughts about the pro's and con's about it, and also how "dangerously" it can impact the entire website ect.
the other option is, o.c., a generic handler (ajaxHandler.ashx).
i am again stating we are talking about IIS7+ where they integrated the pipelines.
p.s.
another thought is to build a WCF that will have to "open" (create instances) of anything that i would already have in my handler/module (in sharepoint for example the SPContext)
regards
Bresleveloper

Autofac lifetime scope issue with asp.net webforms

I'm having an issue with the lifetime scope of autofac lasting across a request in an asp.net webforms site.
I'm register a factory in auto fac thus:
builder.RegisterType<DoSomethingFactory>().As<IDoSomethingFactory>().InstancePerLifetimeScope();
This occurs in the app_start of course.
then I have a simple user control that calls a method of this factory
IDoSomethingFactory doSomethingFactory = Resolver.Resolve<IDoSomethingFactory>();
Number.Text = doSomethingFactory.DoSomething().ToString();
I have two instances of this control on a page, so that the DoSomething method should be called twice and the factory should be resolved twice also.
The first time I run the site, the contstructor for the DoSomethingFactory is fired, and there are 2 subsequent calls to the DoSomething method. The second request, results in 2 calls to the DoSomething method without a fresh new-ing up of the factory.
If I take out the InstancePerLifetimeScope on the registering then the factory is instantiated on each resolve. Most answers I have seen for this talk about an MVC site. I also have an MVC site and am using it in the same manner and it is working as requested, hence the need to question for asp.net webforms
To be clear I would like the factory to be instantiated once every request. Any help or ideas would be welcome.
Many thanks
Will
If you want to have one instance of your DoSomethingFactory per request you need to use the InstancePerHttpRequest extension method.
From the Autofac wiki: WebFormsIntegration
ASP.NET integration adds a special component lifetime that allows a component instance to live for the life of a single HTTP request. You can register components using the InstancePerHttpRequest() extension method in the Autofac.Integration.Web namespace.
So change your registration to:
builder.RegisterType<DoSomethingFactory>()
.As<IDoSomethingFactory>()
.InstancePerHttpRequest();

MVC 3/4 HttpModule or ActionFilter

I need to check some stuff (Cookies) for each request coming to my application.
In ASP.NET we've used HttpModule for this task , the question what should be used in MVC ? Some Global Filter , or I can Use HttpModuler as well, is there Any difference in Request PipeLine between MVC and regular ASP.NET ?
MVC is an abstraction over ASP.NET and therefore their "hooks" really depend at which level you want to inject your logic. An action filter will allow you to hook into MVC specific events:
OnActionExecuting – This method is called before a controller action is executed.
OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.
Whereas an HttpModule only allows you to hook into ASP.NET (upon which MVC is built) specific events:
BeginRequest - Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page), synchronize this event.
AuthenticateRequest - If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password), build a module that synchronizes this event and authenticates the user in a way that you want to.
AuthorizeRequest - This event is used internally to implement authorization mechanisms (for example, to store your access control lists (ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so.
PreRequestHandlerExecute - This event occurs before the HTTP handler is executed.
PostRequestHandlerExecute - This event occurs after the HTTP handler is executed.
EndRequest - Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page.
So it really depends on when you need to hook in your event and which events you need.
If the HttpModule worked well for you before then it will continue to with Mvc.
The other parts of your question are quite broad in scope and think you'd be as well reading a good article on asp.net-mvc pipeline and extensibility.
I've done similar things using a global action filter. It works quite well, and keeps your code integrated within your application.
An HTTP module works as well, of course, but this will mean seperating the code from your main application and maintaining it seperately. Unless your code spans multiple sites or is used in multiple applications, or needs to work with web forms sites, then I would use a global filter.

UpdatePanel behide the scene

The knowledge I have about UpdatePanel is
They use Ajax requests to work asynchronously.
They perform a partial postback.
Now recently I was working on Ajax requests too using $.ajax() method of jQuery when I found some difference about Ajax requests made by me and Ajax requests made by UpdatePanel which are
UpdatePanel's Ajax request perform full page life cycle but my Ajax request calls only that particular method which I have supplied to be called.
Methods called by UpdatePanel doesn't need to be tagged as WebMethod but methods called by my Ajax request has to be WebMethod.
I searched web to get details about these differences but doesn't found any resource, Can someone tell me whats the difference between Ajax calls made by me and by UpdatePanel or more specifically hows those differences made and what special tricks are played by UpdatePanel to achieve that functionality ?
I liked this question mate +1
Basically the evil UpdatePanel is the root of all evil. Sadly it is =(. The update panel behind the scenes raises async postbacks to the server, but to fully understand what happens, you need to understand the UpdatePanel goal
The UpdatePanel was designed to work with the ASP.Net web forms, these controls have to go through the whoooole ASP.Net page life-cycle in order to work correctly, therefore, they need the whoooole page ViewState. So every time you perform a post back using an UpdatePanel the whole page viewstate will be sent to the server back and forth even when you only want to partial render a small part of your page.... sucks. Why did Microsoft created this monster? I think it was because back 5-6 years ago (or more) AJAX was not so popular as it is today. Another reason is that Microsoft wanted to provide a framework to write AJAX calls in a simple way, but without losing the power of the web controls.
So with this in mind, the difference between an UpdatePanel and an AJAX call, is simply:
The AJAX call sends only the data needed by the server method and it returns just the required data. The performance of using pure AJAX calls is impressive.
but methods called by my Ajax request has to be WebMethod.
That's partially true, I mean there are different ways to expose methods from the server:
Using traditional Web Services - Script services (ASMX)
Using PageMethods (static methods on your ASPX pages)
Exposing WCF services
Exposing WCF REST services
Using WEB API
Using MVC controller's actions
Using custom HttpHandlers returning a specific content type like JSON
etc
At the end the result is the same, no matter what approach you use to expose server methods when consuming them with pure AJAX calls you will have to face the following if you are using web forms:
If you want to use pure AJAX calls, then you should consider moving to MVC because in web forms you will lose the power of the web controls, in other words your development would be more difficult
They perform a partial postback.
No, update panels perform a full postback, they just perform a partial update on the page.
UpdatePanel's Ajax request perform full page life cycle but my Ajax request calls only that particular method which I have supplied to be called.
Precisely, the Update panel performs a full postback. Highly inefficient.

Resources