MVC4 Razor View Batch Methods - asp.net-mvc-4

I have a HTML helper which shows translated resources depending on some business logic. Now this helper uses a webservice to load the translated resources.
The problem is that it takes very long if we have to make a webservice call for each single translated resource. Of course we cache the result but the initial call still takes very long.
What would be great would be if we could kind of batch process the translated resources. Like we collect all the resources that are to be rendered and then after we know which resources have to be translated only make one webservice call which translates all the resources for us and renders it to the correct places in the view.
Is there some mechanism in Razor templates for this?

Related

Can Webapi be used in an application which is not excessed by any external application?

I'd read it somewhere that whenever one needs to do data intensive work then Webapi could be used. Ex: autocomplete textbox where we get data from using ajax on key press.
Now someone told me that Webapi shouldn't be used within applications which are not externally accessed. Rather action should be used to the same work as it is capable of returning the data back in a similar fashion to webapi.
I'd like to know your suggestions over it.
Depends on how you look at it. If all you need is ajax-ification of your controller actions, then you really don't need Web-API. Your actions can return a JsonResult and it is very easy to consume that from your client side through an AJAX call.
Web-API makes it easy for you to expose you actions to external clients. It supports HTTP protocol and Json and XML payloads automatically, out of the box, without you writing the code for it. Now, there is nothing preventing you from consuming the same Web-API actions from your own internal clients in an AJAX manner.
So the answer to your question depends on your design. If you don't have external clients, then there is no string need for you to have Web-API. Your standard controller actions can do the job.

MVC - Is It Wrong To Redirect From Model

I would like to ask whether it's a good approach to redirect from within a model instead of a controller.
The reason I want to do that is because it is easier to unit test redirection from a model (I just pass a mock redirector object to the model in my tests) as opposed to controller which is more difficult to unit test. It also keeps controller thinner as all I do in the controller is create an instance of the model and pass it parameters from the request object. There is not a single if/else in the controller this way.
Is it a bad practise?
Most often in webapplications - MVC or not - redirects are implemented on a high-level layer. In non OOP code this often is a high level global function that knows a lot about the global static state and what represents a request and a response therein.
In more OOP driven sites, you find this often as a method with the "response" object (compare Symfony2 and HTTP Fundamentals; note that Symfony2 is not MVC), however, it often then has also some similar methods (e.g. see Difference between $this->render and $this->redirect Symfony2).
As most often those "response" objects are central in the web-application this qualifies as well as a high-level layer in my eyes.
From a testing standpoint - especially with integration testing - you normally do not need to test for redirects specifically. You should test that generally your redirect-functionality works on the HTTP layer so that parts of your application that make use of it can rely on it. Common problems are to not really follow the suggestions given in the HTTP/1.1 specs like providing a response body with redirects. A well working webapplication should honor that. Same for using fully qualified URIs.
So how does all fit this into MVC here? In a HTTP context this could be simplified as the following:
The response is to tell the user to go somewhere else.
If the user would not be important, the application could forward directly - that is executing a different command, the client would not be used for that, the redirect not necessary (sub-command).
The response is to say: Done. And then: See next here this command (in form of an URI).
This pretty much sounds like that the actual redirect is just some output you send to the client on the protocol level in client communication. It belongs into the interface of that protocol you want to support. So not into the model but into the client-interface and the boundary of the client interface inside an MVC application is the controller AFAIK.
So the redirect probably is a view-value-object with a special meaning. To get that working in a HTTP MVC you need a full URL abstraction which most PHP frameworks and libraries make a big round around because it's not well known how that works. So in the end I'd say: Do as Symfony2 has done, place it in a high level layer component, drop MVC and live with the deficiencies.
Everything else is hard to achieve, if you try otherwise, there is high risk to not stop with abstracting anymore.
Neither controller nor model should be redirecting anything anywhere. HTTP Location header is form of a response, which strictly in purview of views.
Model layer deals with business logic, it should be completely oblivious even to the existence of presentation layer.
Basically, it goes down to this: controllers handle input, views handle output. HTTP headers are part of output.
Note: when dealing with Rails clones, it is common to see redirects performed in "controller". It is because what they call "controller" is actually a merger of view and a controller responsibilities. This is a side-effect of opting to replace real views with simple templates as the 3rd side of triad.
I would say yes, it is wrong. As far as I understood, while models manage data and views manage layouts (i.e. how data should be displayed), controllers are only and exclusively in charge of the HTTP requests/responses management (in the case of a web app), and redirections typically belong to that tier in my opinion.
Examples in common frameworks
Symfony:
return $this->redirect($this->generateUrl('homepage'));
Spring MVC:
return "redirect:/appointments";
I think that you could have a model for your applications work flow or navigation (in your model layer) and then have your controller translate the different concepts in your work flow/navigation model into what views are to be displayed.
Your work flow class/module could know about the different activities/phases/steps that are available to the user, and it model your application kind of like a state machine. So your controller would make calls to this module to update the state and would recieve a response telling the controller which activity/phase/step it should go to.
That way your work flow model is easy to test but it still doesn't know about your view technology.
Many mentioned in comments these thoughts, so here is a summary:
The logic to figure out whether you need a redirect and what your redirect should be belongs into the controller. The model simply takes the data a view needs. This happens AFTER you decided which view to render. Think of the redirect as an instruction to perform a different controller action.
I use ASP.NET MVC and the controllers generate a RedirectResult for this purpose, which are completely unit testable. I don't know what is supported in your framework, but this is what MVC would do:
public class MyController : Controller {
public ActionResult ShowInfo(string id) {
if( id == null ) {
return new RedirectResult("searchpage");
} else {
return new ViewResult("displayInfo");
}
}
}
In your unit tests, you instantiate MyController and check the type of the result and optionally, the url or view name.
Whether your redirect is actually performed is not a unit test issue - that's essentially making sure your framework is working right. What you need to test is that you are giving the correct instruction (i.e. the redirect) and the correct url.

Should a Rails 3 RESTful PUT call return the JSON representation of the updated resource?

To be most compatible with practice RESTful service development and existing Javascript MVC frameworks like AngularJS and Ember.js that would be used to integrate with a RESTful service, should a resource be deserialized to JSON from a RESTful PUT call that just updates a resource?
For example, Rails 3.2.8 seems to promote just using respond_with #foobar.update_attributes(...) which just returns an HTTP status code 204. However, you can specify that you want respond_with or respond_to to return the resource.
But, this means that another call must be made to get the resource to get any updates that may have occurred on the resource in addition to the ones that were specified in the PUT call. On one hand it is nice not to have anything returned, because you may not care if it has changed, and this isn't like POST in which you are creating a new resource and may want a full representation with the new id. However, having to make another GET call to get the updated resource following the PUT, though nice that it is intentional, is additional overhead (i.e. for a PUT where you need the updated resource, you would have to PUT and then GET).
I understand that REST leaves a lot open as to implementation, but I'd like to understand what people agree is a good practice with regard to this, at least as of October 2012 in the stated context of being used by AngularJS and Ember.js, and why.

n-tiers, Linq and WCF

We have an n-tiers architecture :
-a WCF Service that communicates with the database and handles all the business logic.
-an ASP.NET MVC website that communicates with the WCF service.
Here is a scenario of data serialization-deserialization from the database to the html view of a 'guitar':
-Guitar_1 a class generated by linq,
-Guitar_2 the DataContract exposed by the WCF service, and consumed by the ASP.NET MVC website.
-Guitar_3 the model passed to the View
When an end user wants to retrieve a guitar, Guitar_1 is transformered into Guitar_2 and then into Guitar_3. That's really not a problem but if the end user requests a list of guitars then all this process is repeated for each guitar (a loop).
If i had to programmatically handle all the serialization-deserialization stuff, i'd had only one class per layer. It could still be done for example on the wcf project by annoting 'DataContract'/'DataMember' on the Linq class, but if I refresh my database model all my annotations disappear (Same case ont the ASP.NET MVC project, refreshing the service reference deletes all the added code).
Also, Is it really more productive to use these automatic serializers? the time taken to write a serializer-deserializer takes as much time as annoting classes (DataContract/DataMember) and handling the conversion of class Guitar_1 to Guitar_2... Add to that the loss of perofrmance (Loop and conversion)...
What do you guys think? Do some of you code as in the old days because of this?
UPDATE: As suggested by 'Abhijit Kadam', I used partial classes when consuming a webservice, however, I found a better solution when using Linq2SQL : POCO classes.
If the main concern is that the model classes created by framework are automatically regenerated and you changes like annotations on such classes are wiped out THEN in this case you can use partial classes, info here. If the auto generated class is Employee. Then in separate file create a partial class Employee and include the fields in this partial defination that you want to annotate. This class will not be wiped out and regenarated. However when you compile the code the resultant Employee class will be combination of the Original Employee class + the partially defined Employee class.
Also converting from class Guitar_1 to Guitar_2 is OK and at times we have to do such things to meet specific requirements. I prefer JSON data to be transferred across the network wire like from WCF to MVC Web and then browser will fetch the json data from the MVC APP. Then I use frameworks like jsrender or knockout to render the data as HTML on the client side(browser). JSON is readable, compact and javascript and javascript libraries love json.

What are the benefits of an ASHX handler file in asp.net?

What are the benefits of using an ashx, or handler? Also, do I need them if I use MVC (and why not)?
Does the framework matter (2.0+)?
Why would I want to use a handler? I was recently recommended to use one for retrieving an image but I don't know why.
Thank you for your time.
Edit - is a handler faster?
Just a few examples:
Dynamic image generation: You can write handlers that return data driven images by creating an ASHX handler that returns image data and then using that URL in your tags. e.g. <img alt="user's custom icon" src="Icon.ashx?username=bob"></img>
Returning REST-based XML or JSON data to AJAX code on the client.
Custom HTML: Return totally custom HTML for a page when the ASP.NET Web Forms or MVC framework is too restrictive
I believe this has been available since 1.0
The purpose of handlers in non-MVC projects is to provide some type of encoded response, outside of HTML. Typically, a handler would return XML (rss, RESTful, etc), JSON for jQuery or other Javascript, or sometimes just pure data such as file binary downloads. I've used handlers to even return special javascript to be excuted on the client, as a way of lazy-loading large binary or requirements on a "demand-only" approach. More or less, a handler would be used to return "anything but HTML".
In MVC, you would move away from handlers and utilize the Controller to return whatever data you like. So, in the method like:
mywebsite.com/restapi/content/56223
You RestfulContentController would have a method for Index(), that would NOT return a View(), but instead pure XML or JSON.
public class JSONContentController : Controller
{
public JsonResult Index(int ContentID)
{
// get Content() by ContentID
//
// return a JSON version
return Content().SerializeToJSON();
}
}
They're very useful if your working in an environment where you do not have access to IIS but want to change things like far-future expiry response headers to optimize caching for files like css, images, JavaScript
For images you can do stuff like on the fly optimization so you can request images like image.jpg.ashx?w=180&quality=70 and then use the handler to deliver the image based on the settings passed in the querystring
aspx inherits page which implements IRequireSessionState. So if you call it via Ajax then asp.net needs to lock the session before further processing.
For ashx file it is stateless.
Unless you inherit it from IRequireSessionState to manage state.
Use ashx for all Ajax calls and use aspx for purely asp.net page.