Here are the steps,
Step 1: Create the basic structure of your project, View and View Model.
Step 2: Create Controller add Action which will return the JSON result, My Controller is as below. Note I have added action which return the JSON result.
- using DropdownGrid.Models;
- using System;
- using System.Web.Mvc;
- namespace DropdownGrid.Controllers
- {
- public class JSONANDAJAXDemoController: Controller
- {
- public ActionResult Index()
- {
- MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
- obj.myTest1ViewModel = new MyTest1ViewModel();
- obj.myTest1ViewModel.MyTestUpdate = "Test1";
- obj.myTest2ViewModel = new MyTest2ViewModel();
- obj.myTest2ViewModel.MyTestUpdate = "Test2";
- return View(obj);
- }
- public JsonResult GetJSONObject()
- {
- MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
- obj.myTest1ViewModel = new MyTest1ViewModel();
- obj.myTest1ViewModel.MyTestUpdate = "Test1" + DateTime.Now.ToString();
- obj.myTest2ViewModel = new MyTest2ViewModel();
- obj.myTest2ViewModel.MyTestUpdate = "Test2" + DateTime.Now.ToString();
- return Json(obj, JsonRequestBehavior.AllowGet);
- }
- }
- }
Step 3: Include jQuery and AJAX in your project.
Case 4: Give call for your JSON action as in the following way,
This is my AJAX call to JSON action.
- <script type="text/javascript">
- $(document)
- .ready(function ()
- {
- $('#Submit')
- .click(function ()
- {
- $.ajax(
- {
- url: '/JSONANDAJAXDemo/GetJSONObject/',
- type: 'get',
- dataType: "json",
- success: successFunc,
- error: errorFunc
- });
-
- function successFunc(data)
- {
- $("#Div1")
- .html('')
- $("#Div1")
- .html("Call using JSON Object : " + data.myTest1ViewModel.MyTestUpdate);
- $("#Div2")
- .html('')
- $("#Div2")
- .html("Call using JSON Object : " + data.myTest2ViewModel.MyTestUpdate);
- }
-
- function errorFunc()
- {
- alert('MVC controller call failed.');
- }
- });
- });
- </script>
Note: You may add table or design in any form of HTML.
Step 5: Include div’s in your code .
- <div id="Div1"> Initial State : @Model.myTest1ViewModel.MyTestUpdate </div>
- <div id="Div2"> Initial State : @Model.myTest2ViewModel.MyTestUpdate </div>
- <input type="submit" value="Load Json Object Data" id="Submit" />
Step 6: Run the project and click on button you will find the JSON data displaying in the Initial view state.
On click load button: