JavaScript Result in Controller Sample in MVC: Day 12

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...".



Step 2

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

Click on the "Add" button.



Step 3

Name the controller as in the following:



And it will add an action result method to the controller.



Step 4

Now we need to create a view.

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



Step 5

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

Click on the "Add" button.



Step 6

Add a title to the index page.



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.



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.



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.



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".



<< Day 11                                                                             >> Day 13


Similar Articles