Wednesday, 9 February 2011

How to use Asp.net mvc JavaScriptResult practically

I am usually very excited about knowing something that can make my life easy and JavaScriptResult is one of that thing. It is used to execute JavaScript code immediately on the client sent from the server. Here is the small code snippet for its implementation.

View: 
<%: Ajax.ActionLink("display", "Display", new AjaxOptions()) %>
<%: Html.TextBox("name","mazhar") %>
<%: Ajax.ActionLink("checks", "Checks", new AjaxOptions()) %> 

Controller:
  public ActionResult Display()
  {        
    var  script = "$('#message').append('Display');";
    return JavaScript(script);
  }

  public ActionResult Checks()
  {        
    string script = "var textboxvalue=$('#name').val();";
    script += "$('#message').append(textboxvalue);";
    return JavaScript(script);
  } 

Output:

1) Clicking on the first link will display Display in the message div.
2) Clicking on the second link will display mazhar in the message div.

It's usage in the light of Asp.net Mvc:

Asp.net mvc is the design pattern which is all about separation of concern . It has the model, view and controller. Each doing it part and not intermingling with each other directly. My Advice would be to not use it but this thing is present if it become necessary.

2 comments:

  1. Can u mention out put result bcoz I’m not near any computers with Visual Studio installed.

    ReplyDelete
  2. It is not working.
    It displays the script in the browser as it is.

    ReplyDelete