JavaScript Result in Controller Sample in MVC

JavaScript Result in Controller Sample in MVC

Introduction

Here we see how to use a JavaScript result in controller in MVC.

Step 1

Create a MVC project from the "Empty" template.

Right-click on "Controllers" and select "Add" >> "Controller...".

image.png

Step 2

Select "MVC 5 Controller - Empty" to add an empty controller.

Click on the "Add" button.

image.png

Step 3

Name the controller as in the following:

image.png

image.png

Step 4

Now we need to create a view.

Right-click on "Index" and select "Add View...".

image.png

Step 5

Name the view and select "Empty (without model)" as the template.

Click on the "Add" button.

image.png

Step 6

Add a title to the index page.

image.png

Step 7

JavaScript result sends JavaScript content to the response. Here we create one div element in the index.cshtml page. We write some text inside the div element. In the JavaScript result method we get a div element and update its content using JavaScript.

image.png

Step 8

Now let's create a link to call the javaScriptResult method of the Home controller. Here we use ajaxhelper to create a link. Ajaxhelper methods are called using "Ajax" property of the view. Using Ajaxhelper we can "submit a form" and "invoke an action method". So here we use Ajaxhelper to invoke the javascriptresult method using Ajax.ActionLink.

image.png

We use "GET" for httpmethod in ajaxoptions. Our updatetargetid is "some-div" since we want to access the content of that div. And we set the insertion mode to "replace" since we need to replace the content inside the div.

image.png

Step 9

Run the project. The "Akshay Patel" string is rendered on the browser. Now click on the JavaScript link and it will update the rendered string to "Akshay Patel - Updated By MVC".

image.png

<< Day 11

>> Day 13