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




Picture showing the project structure of the asp.net mvc project
Click to Enlarge


Adding Files In The Project




  1. Create a sub-folder ‘Test’ inside the ‘Views’ folder.
  2. Inside the ‘Test’ folder, add 2 views ‘Offline.cshtml’ and ‘Online.cshtml’.
  3. Add a new view ‘ConditionalView.cshtml’ inside the ‘Views/Home’ folder.
  4. 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




  1. Offline
  2. 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


Picture showing the output of the conditional view rendering in asp.net mvc
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, September 26, 2017

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250