The use of MVC Javascriptresult

Source: Internet
Author: User

Javascriptresult code Snippets defined in MVC

C # codeCopy
 Public ClassJavascriptresult:actionresult{Public Override voidExecuteresult (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 members    protected   virtual  Javascriptresult JavaScript ( string  script);                  /span>                

Where: The Javascriptresult property script represents the response of the JavaScript script, while the Executeresult method used in response to the JavaScript script, in addition to writing the script content to the current HttpResponse, The media type of the response is also set to "application/x-javascript" (not "Text/javascript").

Second, you can use Contentresult to achieve the same script response function as Javascriptresult

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

C # codeCopy
//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 " ); }                 /span>                

Iii. Examples of Javascriptresult

The following shows an online shopping scene: For the completion of the purchase of goods after the submission of orders, the service side in the processing of orders need to confirm whether the order of goods exceeded the corresponding inventory, if the stock is sufficient to deal with the order, otherwise the inventory is insufficient, And the real-time inventory of goods display to the user let him fix the purchase amount of the corresponding goods. We use JavaScript to prompt the message of the Order Processing result (successful processing or insufficient inventory), it is clear that this JavaScript should be dynamic (inventory is dynamic).

1, define a ShoppingCart class 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 Shoppingcartitem's three attributes (ID, name, and quantity) represent the product ID, the title, and the order quantity, respectively.

C # codeCopy
     Public  class  shoppingcart:list  <  shoppingcartitem ;    {}   public   class  Shoppingcartitem  { public   string  ID   { get ;  set ;}   public   string  Name   { get ;  set ;}   public   int  Quantity   { get  ;  set ;} }                 /span>                 

2. Create one of the following homecontroller. We create a ShoppingCart object with three items in the default action method index and render it as model in the corresponding view. The action method ProcessOrder is used to process the submitted purchase order, and if the quantity of the ordered item does not exceed the inventory amount (represented by a static dictionary field, stock), the alert function is called to prompt the "shopping order successfully processed", otherwise "insufficient inventory" is indicated, and displays the current inventory of the corresponding item.

C # codeCopy
     Public ClassHomecontroller:controller{Private StaticDictionary<String,Int>Stock= NewDictionary<String,Int>();StaticHomeController (){stock. ADD ("001",20); Stock. ADD ("002",30); Stock. ADD ("003",40); } PublicActionResult Index (){ShoppingCart Cart= NewShoppingCart (); Cart. ADD (NewShoppingcartitem{Id= "001", Quantity=1, Name= "Item A"}); Cart. ADD (NewShoppingcartitem{Id= "002", Quantity= 1, Name= "Item B"}); Cart. ADD (NewShoppingcartitem{Id= "003", Quantity= 1, Name= "Product C"});ReturnView (CART); } PublicActionResult ProcessOrder (ShoppingCart cart){StringBuilder SB= NewStringBuilder ();Foreach(Var cartitemInchCart{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 successfully! ‘);  ,  " text/javascript " );   string  script  =   string . Format (  alert (' Insufficient inventory! ({0});  ", sb. ToString (). TrimEnd ( ' ;  ' ));  return  JavaScript (script);   private   bool  checkstock ( string  ID,  int  quantity)   { return  Stock[id]  >=  quantity;} }                 /span>                 

3. Create an action method index corresponding to the view. In a form submitted as an AJAX request (the Action property of the form corresponds to the action method ProcessOrder defined above), the items and quantities in the shopping cart are displayed, used to modify the order quantity and submit the order in the form of an AJAX request by clicking the "Submit Order" button.

C # codeCopy
@model ShoppingCart<Html> <Head> <Title>User Login</Title> <Script type="Text/javascript"Src="@Url. Content ("~/Scripts/Jquery-1.6.2. js")"></Script> 1:<Script type="Text/javascript"Src="@Url. Content ("~/Scripts/Jquery.unobtrusive-Ajax.js")"></Script> </Head> <Body>@using (Ajax.beginform ("ProcessOrder",NewAjaxoptions ())){For( int  I  =   0 ; I  <  model.count; I  + + )   { <  div ;  @Html. hiddenfor (M  =>  M[i]. Id) @Html. Hiddenfor (M  =>  M[i]. Name) @Html. Displayfor (M  =>  M[i]. Name): @Html. Editorfor (M  =>  M[i]. Quantity)  </ div ; }   <  input type  =  " Submit "  Value  =  " Submit order "  /> }   </ body ;   </ html ;                

4. Operation Result: a shopping cart information containing three items will be displayed, when we enter the corresponding order quantity and click "Submit Order", the order Processing result message will bounce out. The displayed message is shown in the case of insufficient inventory.

The use of MVC Javascriptresult

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.