Wednesday, 9 February 2011

How to use 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.

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

  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);


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 Mvc: 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.


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

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