Articles → ASP .NET MVC → Conditional View Rendering In Asp.Net MVC
Conditional View Rendering In Asp.Net MVC
Create A New Asp.Net MVC Project
 
Click to Enlarge
Adding Files In The Project
 
-  Create a sub-folder ‘Test’ inside the ‘Views’ folder.
- Inside the ‘Test’ folder, add 2 views ‘Offline.cshtml’ and ‘Online.cshtml’.
- Add a new view ‘ConditionalView.cshtml’ inside the ‘Views/Home’ folder.
- Add a new controller ‘TestController’.
Adding Action Method In Testcontroller
 
using System.Web.Mvc;
namespace ConditionalViewDemo.Controllers {
  public class TestController: Controller {
    // GET: Test
    [HttpGet]
    public ActionResult Index(string test) {
      if (test == "A") return View("Offline");
      else return View("Online");
    }
  }
}
Adding Buttons In Conditionalview
 
- Offline
- Online
@model ConditionalViewDemo.Models.ConditionalViewModal
@{
    ViewBag.Title = "View";
}
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<button id="btnOffline">Offline</button>
<button id="btnOnline">Online</button>
<div id="test"></div>
<script>
    $('#btnOffline').click(
        function(){
            $.ajax({
                url: "/Test/Index",
                type: "GET",
                data: {test: 'A'},
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#test").html(data);
                },
                error: function () {
                    alert("An error has occured!!!");
                }
            });
    }
    );
    $('#btnOnline').click(
      function () {
          $.ajax({
              url: "/Test/Index",
              type: "GET",
              data: { test: 'B' },
              contentType: "application/json; charset=utf-8",
              success: function (data) {
                  $("#test").html(data);
              },
              error: function () {
                  alert("An error has occured!!!");
              }
          });
      });
</script>
Output
 
Click to Enlarge
| Posted By  - | Karan Gupta | 
|  | 
| Posted On  - | Tuesday, September 26, 2017 |