Understanding the nature of several actionresult of asp.net mvc: Javascriptresult & Jsonresult

Source: Internet
Author: User
Tags abstract visual studio

In the previous two articles ("Emptyresult & Contentresult" and "Fileresult") we analyzed Emptyresult, The three actionresult of Contentresult and Fileresult respond to the results of action execution to the client. This article focuses on the two actionresult that are often used in Ajax calls, namely Javascriptresult and Jsonresult.

First, Javascriptresult

Javascriptresult allows us to dynamically generate a JavaScript script on the server side as a response to the request, which is executed on the client. In fact, the implementation of Javascriptresult is very simple, it simply will represent the JavaScript script string through the current HttpResponse response to the requesting client. As shown in the following code snippet, Javascriptresult's property script represents the JavaScript script for the response. In addition to writing script content to the current HttpResponse, the Executeresult method for responding to JavaScript scripts also sets the media type of the response to "Application/x-javascript" (not "text/ JavaScript ").

   1:public class Javascriptresult:actionresult
2: {
3: Public override void Executeresult (ControllerContext context)
4: {
5: httpresponsebase response = context. Httpcontext.response;
6: Response. ContentType = "Application/x-javascript";
7: Response. Write (this. Script);
8: }
9: Public string Script {get; set;}
10:}
11:
12:public abstract class Controller:controllerbase, ...
13: {
: //other Members
: protected Virtual Javascriptresult JavaScript (string script);
16:}

The abstract class controller defines a javascriptresult as the previous JavaScript method creates based on the specified script string. In fact, we can achieve the same script response function as Javascriptresult by Contentresult, the following two-part program is equivalent. Most browsers equate the media type "Application/x-javascript" with "Text/javascript", so the media type is set to "Text/javascript" when a script response is made through Contentresult Can play the same effect. The action method that returns a type of Javascriptresult is typically used to handle AJAX requests.

   1://javascriptresult:
2:public class Foocontroller:controller
3: {
4: Public actionresult JavaScript ()
5: {
6: Return JavaScript ("alert (' Hello world! ');");
7: }
8:}
9:
Ten://contentresult:
11:public class Foocontroller:controller
12: {
Public ActionResult JavaScript ()
: {
: Return Content ("alert (' Hello world! ');", "application/x-javascript");
: }
17:}

Example Demo: JavaScript that returns fields automatically executed at the client via Javascriptresult

We routinely demonstrate an example of a script response through Javascriptresult. We demonstrate an online shopping scene: Used to complete the purchase of goods after the submission of orders, the server in the processing of orders need to confirm whether the order of goods exceeded the corresponding inventory, if the stock is sufficient to handle the normal order, otherwise prompted inventory, And the real time inventory of goods displayed to the user to let him revise the corresponding purchase quantity of goods. We use JavaScript to prompt the message of the Order Processing results (successful processing or insufficient inventory), and obviously this javascript should be dynamic (inventory is dynamic).

Define a ShoppingCart class in an empty Web application created through the ASP.net MVC project template in Visual Studio to represent the shopping cart. As shown in the following code snippet, ShoppingCart is a list of Shoppingcartitem objects that represent the shopping cart item, and the Shoppingcartitem three properties (ID, name, and quantity) represent the product ID, name, and order quantity, respectively.

   1:public class Shoppingcart:list<shoppingcartitem>
2: {}
3:
4:public class Shoppingcartitem
5: {
6: Public string Id {get; set;}
7: Public string Name {get; set;}
8: public int Quantity {get; set;}
9:}

Then we create a homecontroller as follows. We create a ShoppingCart object containing three items in the default action method index and present it as model in the corresponding view. Action method ProcessOrder is used to process submitted purchase orders, if the number of items ordered is not over inventory (represented by the stock in a static dictionary field), the prompt "Purchase order successfully processed" by calling the alert function prompts "insufficient inventory". and the current inventory of the corresponding commodity display.

1:public class Homecontroller:controller
2: {
3:private static dictionary<string, int> stock = new dictionary<string, int> ();
4:static HomeController ()
5: {
6:stock. ADD ("001", 20);
7:stock. ADD ("002", 30);
8:stock. ADD ("003", 40);
9:}
10:public ActionResult Index ()
11: {
12:shoppingcart cart = new ShoppingCart ();
13:cart. ADD (new Shoppingcartitem {Id = "001", quantity=1, Name = "Commodity a"});
14:cart. ADD (new Shoppingcartitem {Id = "002", Quantity = 1, Name = "Commodity B"});
15:cart. ADD (new Shoppingcartitem {Id = "003", Quantity = 1, Name = "Commodity C"});
16:return View (CART);
17:}
18:
19:public actionresult processorder (ShoppingCart cart)
20: {
21:stringbuilder sb = new StringBuilder ();
22:foreach (var cartitem in cart)
23: {
24:if (! Checkstock (Cartitem.id, cartitem.quantity))
25: {
26:SB. Append (String. Format ("{0}: {1};", Cartitem.name,stock[cartitem.id]));
27:}
28:}
29:if (String. IsNullOrEmpty (sb.) ToString ()))
30: {
31:return Content (' Alert (' Order successfully processed! '); "," text/javascript ");
32:}
33:string script = string. Format (' alert (' Insufficient stock! ({0}); ", Sb. ToString (). TrimEnd (';'));
34:return JavaScript (script);
35:}
56|
37:private bool Checkstock (string ID, int quantity)
38: {
39:return Stock[id] >= quantity;
40:}
41:}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.