.net mvc design ajax calls (Where to put ajax methods) - asp.net-mvc

Hi
When migrating from ASP.NET to MVC ASP.NET it looks like the MVC is more AJAX friendly.
but still I run into design issue,
Does someone knows Microsoft intention about the design when calling AJAX methods?
Where do I need to put this methods by default, in a separate controller, the same controller?
Is there any kind of official info about it?
Thanks

I don't think that there is any official best practices. Personally I like to follow RESTful conventions when organizing cotrollers and actions no matter how those actions are consumed (AJAX or not).

You might wanna try on having a review on some asp.net samples here. This will give you some ideas. :)

I would suggest taking SessionState into consideration when making the choice of method placement.
For instance, I would move ajax actions into a separate controller if I am using session state in regular actions, but not in ajax actions (which makes sense for me) and I would like the ajax methods to execute asynchronously. Then I put those ajax methods in a separate controller and mark the controller as [SessionState(SessionStateBehavior.Disabled)] (or ReadOnly). I have found this to be a great improvement in terms of performance.
Note, that you use Session when you use TempData, ViewData or ViewBag variables.
SessionState is explained here:
ASP.NET MVC and Ajax, concurrent requests?

Related

Where best to POST changes made in an ASP.NET MVC non-form view?

I am fairly experienced with AngularJS and in the process of coming to terms with ASP.NET MVC while working with an existing application.
I am having trouble finding a satisfactory way to post changes to data in controls that are not in a webform. ASP.NET MVC has a clean and well documented mechanism for posting web form data, but the "right" way to get data from a view into a model with no submit event eludes me.
The code I am working with uses Ajax to achieve this, but I find it jarring to see a view requiring knowledge of communications protocols and addresses. To me this makes the object a hybrid between view and controller.
So where does such a call belong?
The View? Is my opinion expressed above wrong?
The Model? I don't think so. The model should not be concerned with how it is moved around IMO. It would become a model/controller.
The Controller? Seems the right place to me, but we have very strong positions against this expressed, for example, here: ASP.NET MVC: Access controller instance from view
I can't help feeling that there's a mechanism in ASP.NET MVC to POST non-webform values nearly as cleanly as webform values, but in the absence of such a beast I have to choose whether to place HTTP calls in either M, V or C.
I hope this isn't a stupid question.

How to handle callbacks in asp.net?

Are there different callbacks available in asp.net like rails provide before_validation, before_update, before_save and before_destroy?
How to handle this scenarios in asp.net?
Take a look at the concept of Filters in ASP.NET MVC and also to the following 4 methods in the controller base class: OnActionExecuting, OnResultExecuting, OnAuthorization, and OnException.
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting.aspx-
Update
On a second though I just realize that you might be looking for methods at the Model level and I answered from the Controller level. Unfortunately from what I understand that ASP.NET MVC does not provide as much at the Model level as Ruby On Rails does.
It looks like the link is broken so i'll pitch in.
In MVC you would use Action Filters
http://www.asp.net/mvc/tutorials/understanding-action-filters-cs
edit (I see you tagged as mvc but anyhow)
In Web Forms the onLoad method is run before each page action
Using a base class can span it over multiple pages

ASP.NET MVC 2 user control caching

I've recently decided to try out MVC 2 and coming from a webforms background, I'm having a little trouble trying to figure out the best practice solution to caching data provided to a partial view (user control).
In my webforms application, I have an AccountSummary.aspx page, which has a Booking.ascx control. Booking.ascx had output caching of 300 seconds and in the Page_Load of AccountSummary.aspx, I used to check if the control was null, and if not, pass it a UserId. Then in the code-behind of the Booking.ascx, I used to make a data access call to fetch all the bookings, thus a call to fetch the bookings was made at most once every 300 seconds.
I would like to achieve the same in MVC2, but I can't seem to find the best way of achieving this because all the examples on the web seem to pass the data to the user control in the RenderPartial HTML helper method (which I don't want because on every page load I would have to pass the booking info which is going to kill my database!)
Please advise :-)
Cheers, A.
There is no simple mechanism for view-level caching in ASP.NET MVC 2.
There are some clever tricks to exploit the output caching in ASP.NET, like Donut Caching and Donut Hole Caching, but they both violate the MVC pattern (by making the DAL spill over into the views, for example), are very tricky to get right, and exhibit virtually undocumented behavior. (See the comments in the blog posts and other posts here on SO for more information.)
The short answer is that view-level caching (i.e. caching a partial view or a view, as opposed to an action method) is a trip you do not want to embark on if you are new to ASP.NET MVC. Hence, you should cache in your DAL instead, or on your action methods.
In your example, you could have a OutputCacheAttribute on an action method that returns a partial view with the booking list, or you could use the System.Web.Cache to cache the booking list when retrieving it in your DAL.

Building a complex page in asp.net MVC

I am currently considering the best way of building a relatively complex page in asp.net mvc. The page (and pages like it) will contain numerous 'controls' such as a shopping basket, recent news widget, login controls and more. In other words, it will be very component based.
My question is, what is the best way of building something like this in asp.net MVC? In regular webforms the answer would be simple thanks to user controls and the fact they can be nicely self contained. In MVC, I understand that in theory I should probably build a viewmodel that includes all the data needed for all my widgets and then render partial views in whatever page I'm building.
Could an alternative approach be to use javascript to load widgets 'dynamically' (think jQuery load) by simply calling into controllers that render partial views. That way I could have a basket controller, which when called renders out a basket. Of course, this relies on javascript....
Whats the best practise for situations like this?
Thanks
You could of course use JavaScript to populate the page sections but then this content will not be accessible to search engines (but that probably does not concern you).
What you need to understand that there is currently no way to make these partial views perform independently. Like talking to their own controller and posting data while having the rest of the stay unchanged (like it could have been done with WebForms and user controls). If you think postbacks and control state these things do not exist any longer. Your "control" makes a post, the controller has to process the request and then recreate the complete view along with all element values, states and other "user controls".
Unless you do it asynchronously with JavaScript of course. But then it's not gonna be an accessible page any more.
You can try SubControllers from MvcContrib or Steve Sanderson`s "Partial Request" approach.
But i warn you - communication between (partial requests, i haven't tried subcontrollers myself) them might get tricky and lead to mega failure. Use them only if you are completely sure that they are completely independent.
Anyway - that's a bad idea and should be avoided through controller/viewmodel inheritance or something....
My understanding of MVC is not yet up with WebForms, however is the generally accepted approach for stuff like this to simply throw these things in the ViewBag rather than include them in the ViewModel?
You could send down a main view model with some simple checks on it. Then render the appropriate Action if required. Then each partial could use it's own viewmodel and you wouldn't need to send everything down initially on the same viewmodel.
Razor:
#if (model.ShowShoppingCart)
{
#Html.Action("Index","ShoppingCart")
}
#if (model.blah)
{
#Html.Action("Index","blah")
}

Does the concept of a Control make sense in MVC?

I've started using MVC reccently, and one thing that occurs to me is whether its possible for the concept of a Control to exist in MVC?
From what I see the framework allows the application to be nicely factored into Models, Views and Controllers, but I can't think of a nice way to take a "vertical slice" of that application and reuse it in another application.
What I mean by that is it strikes me that any UI components I build with MVC maybe not very amenable to reuse, in the same way you can reuse a Contol in ASP.NET WebForms. Ok, there are HTML Helpers but I am thinking of something more modular. Something more like the control model in WPF.
Does this dichotomy go to the heart of MVC vs WebForms, or can reusable UI components work in an MVC world?
You can still use ascx files and other features in ASP.NET Web Forms. The only missing piece in MVC is the postback model and view state oriented state management. There is no <form runat="server"> anymore and no automatically generated hidden fields. Except these, all other features can be used in ASP.NET MVC. You can still write controls that post data using a REST based mechanism and use them in your views.
So, yes, as long as your controls don't rely on a server side form for postback, you can use them exactly the same way you'd use in ASP.NET Web Forms.
I was looking for the same thing - for reusable widgets with their own data paths and found this on Steve Sanderson's Blog:
http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/
From the article:
"You’ve heard of partial views, so how about partial requests? Within any MVC request, you can set up a collection of internal partial requests, each of which can set up its own internal partial requests and so on. Each partial request renders a plain old action method in any of your plain regular controllers, and each can produce an independent widget."
This article respectfully offers a alternative to The MVC Contrib Group's Sub Controller strategy (http://www.mvccontrib.org/) which is also a solution for what you are looking for.
I guess its harder in MVC to completely encapsulate rendering and post back handling in a single control you just drop on a page. It some ways this is because ASP.NET Webforms is very abstracted from HTTP semantics and that abstraction is a framework where its possible to create reusable user controls.
ASP.NET MVC doesn't have the abstraction of webforms so you can have a control the posts to three different controllers. While it may feel like your losing easy to use controls when you move to ASP.NET MVC, I think you have a better framework for separating and reusing domain logic.
In ASP.NET MVC you have partial views which can be reused. Rob Conery has a good post on this: ASP.NET MVC: Using UserControls Usefully
I think the closest thing you'll get to an old school controls are partial views, these are effectively just shared markup that you can drop on any page. However they don't have their own controllers out of the box so the code to power the shared UI component (the partial view) would need to exist in the controller of every page that used it. There are ways to reduce the duplication of code but without implementing partial view controllers and binding I don't think there is a way around it completely.

Resources