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













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










@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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250