Mvc JavaScriptResult usage, javascriptmvc

Source: Internet
Author: User

Mvc JavaScriptResult usage, javascriptmvc

I. snippet of code defined by JavaScriptResult in MVC

C # code Replication
Public class JavaScriptResult: ActionResult {public override void ExecuteResult (ControllerContext context) {HttpResponseBase response = context. httpContext. response; response. contentType = "application/x-javascript"; response. write (this. script) ;}public string Script {get; set ;}} public abstract class Controller: ControllerBase ,... {// other member protected virtual JavaScriptResult JavaScript (string script );}

 

Among them: the Script criptresult attribute Script represents the JavaScript Script for the response, and the ExecuteResult method used to respond to the JavaScript Script not only writes the Script content to the current HttpResponse, the response media type is set to "application/x-javascript" (not "text/javascript ").

 

2. You can use ContentResult to implement the same script response function as JavaScriptResult.

 

For example, the following two sections of code have the same effect.

C # code Replication
//JavaScriptResult:     public class FooController : Controller     {         public ActionResult JavaScript()         {             return JavaScript("alert('Hello World!');");         }     }          //ContentResult:    public class FooController : Controller    {        public ActionResult JavaScript()        {            return Content("alert('Hello World!');", "application/x-javascript");        }    }

 

 

Iii. criptresult instance

 

The following shows an online shopping scenario: after purchasing a product, the server submits an order. when processing the order, the server needs to confirm whether the purchased product has exceeded the corresponding inventory, if the inventory is sufficient, the order will be processed normally. Otherwise, the system prompts that the inventory is insufficient and displays the real-time inventory of the goods to the user to allow him to correct the purchase volume of the corresponding goods. We use JavaScript to prompt messages about the order processing result (successful processing or insufficient inventory). Obviously, this JavaScript should be dynamic (inventory is dynamic ).

 

1. Define a ShoppingCart class to indicate the shopping cart. As shown in the following code snippet, ShoppingCart represents a list of ShoppingCartItem objects for the shopping cart item. ShoppingCartItem's three attributes (Id, Name, and Quantity) represent the item ID, Name, and order Quantity respectively.

C # code Replication
     public class ShoppingCart : List<ShoppingCartItem>     {}           public class ShoppingCartItem     {         public string     Id { get; set; }         public string     Name { get; set; }         public int        Quantity { get; set; }     }

 

 

2. Create a HomeController. In the default Action method Index, we create a ShoppingCart object that contains three items and render it as a Model in the corresponding View. The Action method ProcessOrder is used to process the submitted purchase order. If the number of purchased items does not exceed the inventory (indicated by a static dictionary field "stock ), you can call the alert function to prompt "successful processing of shopping orders". Otherwise, the system prompts "insufficient inventory" and displays the current inventory of the corresponding products.

 

C # code Replication
Public class HomeController: Controller {private static Dictionary <string, int> stock = new Dictionary <string, int> (); static HomeController () {stock. add ("001", 20); stock. add ("002", 30); stock. add ("003", 40);} public ActionResult Index () {ShoppingCart cart = new ShoppingCart (); cart. add (new ShoppingCartItem {Id = "001", Quantity = 1, Name = "commodity A"}); cart. add (new ShoppingCartItem {Id = "002 ", Quantity = 1, Name = "commodity B"}); cart. add (new ShoppingCartItem {Id = "003", Quantity = 1, Name = "commodity C"}); return View (cart);} public ActionResult ProcessOrder (ShoppingCart cart) {StringBuilder sb = new StringBuilder (); foreach (var cartItem in cart) {if (! CheckStock (cartItem. id, cartItem. quantity) {sb. append (string. format ("{0 }:{ 1};", cartItem. name, stock [cartItem. id]) ;}} if (string. isNullOrEmpty (sb. toString () {return Content ("alert ('shopping order processed! '); "," Text/javascript ");} string script = string. Format (" alert ('out of stock! ({0}) '); ", sb. toString (). trimEnd (';'); return JavaScript (script);} private bool CheckStock (string id, int quantity) {return stock [id] >= quantity ;}}

 

3. Create the View corresponding to the Index of the Action method. The items and quantity in the shopping cart are displayed in a form submitted with an Ajax request (the Action attribute of the form corresponds to the ProcessOrder defined above, you can modify the order quantity and click "Submit order" to submit the order in Ajax request mode.

 

C # code Replication
@ Model ShoppingCart 

 

4. Running result: a shopping cart containing three items will be displayed. When we enter the corresponding order quantity and click "Submit order", the order processing result message will pop up. The message is displayed when the stock is insufficient.

 

 


MVC JavaScriptResult

// Controller public JavaScriptResult test () {return JavaScript ("alert (1);") ;}// js $. ajax ({url: "/Ajax/test", dataType: "script", success: function (data) {data ;}});//



 
In the net MVC3 framework, how does one run javascript code pages? It can also be said how to call the javascript Method

If all the forms are filled, click the OK button: <input type = "button" onclick = "fn ()" value = "OK"/>, in this way, you can call that method. If you are not sure, add alert (1) to the first sentence of the method and try again.

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.