JavaScript Result in ASP.NET

JavaScript Result in ASP.NET MVC

In this article, I am going to discuss the JavaScript Result in the ASP.NET MVC application. Please read our previous article where we discussed Json Result in ASP.NET MVC. ASP.NET MVC has different types of Action Results. Each action result returns a different format of the output. As a programmer, we need to use different action results to get the expected output. Action Results return the result to the view page for the given request. 

JavaScript Result in ASP.NET MVC:

Another potentially dangerous ActionResult is JavaScriptResult, which returns a script that is to be executed by the browser. Let us understand JavaScriptResult in ASP.NET MVC with an example.

Step 1: Add this JavaScriptResult() method in home controller.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public JavaScriptResult WarningMessage()
    {
        var msg = "alert('Are you sure want to Continue?');";
        return new JavaScriptResult() { Script = msg };
    }
}
Step 2: Open Index.cshtml and add the following code.
@{
    ViewBag.Title = "DOT NET TUTORIALS";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<div class="jumbotron">
    <h2 style="color:chocolate">Welcome to Dot Net Tutorials</h2>
</div>
<script>
    $(document).ready(function () {
        $("button").click(function () {
            $.getScript("/Home/WarningMessage");
        });
    });
</script>
<button>Show Message</button>

When you run the application and navigate to Home/Index, you will get the following webpage.

JavaScript Result in ASP.NET MVC

And when you click on the Show Message button, it will display the popup as shown in the below image.

JavaScript Result in ASP.NET MVC

This can be really useful for MVVM scenarios and other dynamic script scenarios, but be cautious about using it, as it potentially violates the separation of concerns by making the Controller in charge of View functionality.

In the next article, I am going to discuss FileResult in ASP.NET MVC Application. Here, in this article, I try to explain JavaScript Result in ASP.NET MVC application with examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article. 

1 thought on “JavaScript Result in ASP.NET”

Leave a Reply

Your email address will not be published. Required fields are marked *