Top 55 MVC Interview Questions & Answers (2021 Update)


1) What is Model-View-Controller?

MVC is a software architecture pattern for developing web applications. It is handled by three objects, Model, View, and Controller.

2) What does Model-View-Controller represent in an MVC application?

In an MVC model,

  • Model– It represents the application data domain. In other words, an application’s business logic is contained within the model and is responsible for maintaining data.
  • View– It represents the user interface with which end-users communicate. In short, all the user interface logic is contained within View.
  • Controller- It is the controller that answers the user’s actions. Based on the user actions, the respective controller responds within the model and chooses a view to render that displays the user interface. The user input logic is contained within the controller.

3) Name the assembly to define MVC

The MVC framework is defined in System.Web.Mvc assembly.


4) What are the different return types of a controller action method

Here are different return types of a controller action method:

  • View Result
  • JavaScript Result
  • Redirect Result
  • JSON Result
  • Content Result

5) What is the difference between adding routes to a webform application and an MVC application?

To add routes to a webform application, we use MapPageRoute() method of the RouteCollection class, while for adding routes to an MVC application, we use MapRoute() method.

6) What are the two ways to add constraints to a route?

The two methods to add constraints to a route is

  • Use regular expressions
  • Use an object that implements IRouteConstraint Interface

7) What are the advantages of MVC?

  • MVC segregates your project into a different segment, and it becomes easy for developers to work on
  • It is easy to edit or change some part of your project that benefits in less development and maintenance cost of the project
  • MVC makes your project more systematic
  • It represents a clear separation between business logic and presentation logic
  • Each MVC object has different responsibilities
  • The development progresses in parallel
  • Easy to manage and maintain
  • All classes and objects are independent of each other

8) What “beforeFilter()”,”beforeRender” and “afterFilter” functions do in Controller?

  • beforeFilter(): This function runs before every action in the controller. It’s the right place to check for an active session or inspect user permissions.
  • beforeRender(): This function is called after controller action logic, but before the view is rendered. This function is not often used but may be required if you are calling render() manually before the end of a given action.
  • afterFilter(): This function is called after every controller action and after rendering is done. It is the last controller method to run.


9) What is the role of components Presentation, Abstraction, and Control in MVC?

Here is the role of components Presentation, Abstraction, and Control in MVC:

  • Presentation: It is the visual representation of a specific abstraction within the application
  • Abstraction: It is the business domain functionality within the application
  • Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system

10) What are the drawbacks of the MVC model?

Here are some important drawbacks of the MVC model:

  • The model pattern is a little complex.
  • Inefficiency of data access in view.
  • With a modern user interface, it is difficult to use MVC.
  • You need multiple programmers for parallel development.
  • Multiple technology knowledge is required.

11) What is the role of “ActionFilters” in MVC?

In MVC, “ActionFilters” help you to execute logic while MVC action is executed or it is executing.

12) What are the steps for the execution of an MVC project?

The steps for the execution of an MVC project includes:

  • Receive the first request for the application
  • Perform routing
  • Create an MVC request handler
  • Create Controller
  • Execute Controller
  • Invoke action
  • Execute Result

13) What is routing and three segments?

Routing helps you to decide a URL structure and map the URL with the Controller.

The three segments that are important for routing are:

  • ControllerName
  • ActionMethodName
  • Parameter

14) How routing is done in the MVC pattern?

There is a group of routes called the RouteCollection, which consists of registered routes in the application. The RegisterRoutes method records the routes in this collection. A route defines a URL pattern and a handler to use if the request matches the pattern.

The first parameter to the MapRoute method is the name of the route. The second parameter will be the pattern to which the URL matches. The third parameter might be the default values for the placeholders if they are not determined.

15) How can you navigate from one view to other view using a hyperlink?

By using “ActionLink” method as shown in the below code. The below code will make a simple URL that helps to navigate to the “Home” controller and invoke the “GotoHome” action.

Collapse / Copy Code

<%= Html.ActionLink("Home", "Gotohome") %>

16) How are sessions maintained in MVC?

Sessions can be maintained in MVC in three ways: tempdata, viewdata, and viewbag.


17) What is the difference between Temp data, View data, and View Bag?

  • Temp data: It helps to maintain data when you shift from one controller to another controller.
  • View data: It helps to maintain data when you move from controller to view.
  • View Bag: It’s a dynamic wrapper around view data.

18) What is a partial view in MVC?

Partial view in MVC renders a portion of view content. It is helpful in reducing code duplication. In simple terms, the partial view allows rendering a view within the parent view.

19) How can you implement Ajax in MVC?

In MVC, Ajax can be implemented in two ways

  • Ajax libraries
  • Jquery

20) What is the difference between “ActionResult” and “ViewResult”?

“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class. “ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and “ViewResult”.

“ActionResult” is best if you are deriving different types of views dynamically.

21) How can you send the result back in JSON format in MVC?

In order to send the result back in JSON format in MVC, you can use “JSONRESULT” class.

22) What is the difference between View and Partial View?

Here is the difference between View and Partial View

View Partial View
It contains the layout page It does not contain the layout page
Before any view is rendered, viewstart page is rendered Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml.page
View might have markup tags like body, html, head, title, meta etc. Partial view is designed specially to render within the view, and just because of that it does not consist any markup
View is not lightweight as compare to Partial View We can pass a regular view to the RenderPartial method

23) What are the types of results in MVC?

In MVC, there are twelve types of results in where “ActionResult” class is the main class while the 11 are their sub-types:

  • ViewResult
  • PartialViewResult
  • EmptyResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • JavaScriptResult
  • ContentResult
  • FileContentResult
  • FileStreamResult
  • FilePathResult

24) What is the importance of NonActionAttribute?

All public methods of a controller class are treated as the action method if you want to prevent this default method, then you have to assign the public method with NonActionAttribute.

25) What is the use of the default route {resource}.axd/{*pathinfo}?

The default route prevents requests for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.

26) What is the order of the filters that get executed, if multiple filters are implemented?

The filter order would be like:

  • Authorization filters
  • Action filters
  • Response filters
  • Exception filters

27) What ASP.NET filters are executed in the end?

In the end “Exception Filters” are executed.

28) What are the file extensions for razor views?

For razor views, the file extensions are

  • .cshtml: If C# is the programming language
  • .vbhtml: If VB is the programming language

29) What are the two ways for adding constraints to a route?

Two methods for adding constraints to the route are:

  • Using regular expressions
  • Using an object that implements IRouteConstraint interface

30) What are two instances where routing is not implemented or required?

Two instances where routing is not required are

  • When a physical file is found that matches the URL pattern
  • When routing is disabled for a URL pattern

31) What are the features of MVC?

Here are the features of MVC:

  • Easy and frictionless testability. Highly testable, extensible, and pluggable framework.
  • Offers full control over your HTML as well as your URLs
  • Leverages existing features provided by ASP.NET, JSP, Django, etc.
  • Clear separation of logic: Model, View, Controller. Separation of application tasks via business logic, Ul logic, and input logic.
  • URL Routing for SEO Friendly URLs. Powerful URL- mapping for comprehensible and searchable URLs.
  • Support for Test Driven Development (TDD).

32) What are the real-life example of MVC?

Here is a real-life example of MVC:

  • Let’s assume you go to a restaurant. You will not go to the kitchen and prepare food which you can surely do at your home. Instead, you just go there and wait for the waiter to come on.
  • Now the waiter comes to you, and you just order the food. The waiter doesn’t know who you are and what you want he just written down the detail of your food order.
  • Then, the waiter moves to the kitchen. In the kitchen, the waiter does not prepare your food.
  • The cook prepares your food. The waiter is given your order along with your table number.
  • Cook then prepares food for you. He uses ingredients to cook the food. Let’s assume that you ordered a vegetable sandwich. Then he needs bread, tomato, potato, capsicum, onion, bit, cheese, etc., which the sources from the refrigerator
  • Cook finally hands over the food to the waiter. Now it is the job of the waiter to move this food outside the kitchen.
  • Now the waiter knows which food you have ordered and how it is served.

In this case,

View= You
Waiter= Controller
Cook= Model
Refrigerator= Data

33) What is the difference between 3-tier Architecture and MVC Architecture?

Here is a difference between 3-tier Architecture and MVC Architecture:

Parameter 3-Tier Architecture MVC Architecture
Communication This type of architecture pattern never communicates directly with the data layer. All layers communicate directly using triangle topology.
Usage 3-tier: widely used in web applications where the client, data tiers, and middleware run on physically separate platforms. Generally used on applications that run on a single graphical workstation.

34) How can you use MVC architecture in JSP?

Following example shows the use of MVC architecture in JSP:

  • We are taking the example of a form with two variables, “email” and “password” which is our view layer.
  • Once the user enters email, and password and clicks on submit, then the action is passed in mvc_servlet where email and password are passed.
  • This mvc_servlet is controller layer. Here in mvc_servlet, the request is sent to the bean object, which acts as a model layer.
  • The email and password values are set into the bean and stored for further purposes.
  • From the bean, the value is fetched and shown in the view layer.

Mvc_example.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MVC Guru Example</title>
</head>
<body>
<form action="Mvc_servlet" method="POST">
Email: <input type="text" name="email">
<br />
Password: <input type="text" name="password" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Mvc_servlet.java

package demotest;
  
import java.io.IOException;
  
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
/**
 * Servlet implementation class Mvc_servlet
 */
public class Mvc_servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Mvc_servlet() {
        super();
        // TODO Auto-generated constructor stub
    }
  
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String email=request.getParameter("email");  
        String password=request.getParameter("password");
         
        TestBean testobj = new TestBean();
        testobj.setEmail(email);
        testobj.setPassword(password);
        request.setAttribute("gurubean",testobj);
        RequestDispatcher rd=request.getRequestDispatcher("mvc_success.jsp");  
        rd.forward(request, response); 
    }
  
}

TestBean.java

package demotest;
  
import java.io.Serializable;
  
public class TestBean implements Serializable{
    
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    private String email="null";
    private String password="null";
}

Mvc_success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@page import="demotest.TestBean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Success</title>
</head>
<body>
<%  
TestBean testguru=(TestBean)request.getAttribute("gurubean");  
out.print("Welcome, "+testguru.getEmail());  
%>
</body>
</html>

35) How MVC works in Spring?

Here is how MVC works in Spring:

  • DispatcherServlet receives a request.
  • After that, the DispatcherServlet communicates with HandlerMapping. It also revokes the controller associated with that specific request.
  • The Controller processes this request by calling the service methods, and a ModelAndView object is returned by the DispatcherServlet.
  • The view name is sent to a ViewResolver to find the actual View to invoke.
  • After that, DispatcherServlet is passed to View to render the result.
  • By using the model data, the View renders and sends back result back to the user.

36) What are the important points to remember while creating an MVC application?

Here are some important points to remember while creating an MVC application:

  • You need to remember that ASP.net MVC is not a replacement for ASP.Net web forms-based applications
  • The approach of MVC app development must be decided based on the application requirements and features provided by ASP.net MVC to suit the specific development needs.
  • Application development process with ASP.NET MVC is more complex compared with web forms-based applications.
  • Application maintainability is always higher with the separation of application tasks.

37) What is the difference between Web Forms and MVC?

Here is a difference between Web Forms and MVC:

Parameters Web Forms MVC
Model Asp.Net Web Forms follow event-driven development model. Asp.Net MVC uses MVC pattern-based development model.
Used Since Been around since 2002 It was first released in 2009
Support for View state Asp.Net Web Forms supports view state for state management at the client-side. .Net MVC doesn’t support view state.
URL type Asp.Net Web Forms has file-based URLs. It means file name exists in the URLs, and they must exist physically. Asp.Net MVC has route-based URLs that means URLs are redirected to controllers and actions.
Syntax Asp.Net MVC follows Web Forms Syntax. Asp.Net MVC follows the customizable syntax.
View type Web Forms views are tightly coupled to Code behind(ASPX-CS), i.e., logic. MVC Views and logic are always kept separately.
Consistent look and feels It has master pages for a consistent look. Asp.Net MVC has layouts for a consistent look.
Code Reusability Web Forms offers User controls for code re-usability. Asp.Net MVC offers partial views for code re-usability.
Control for HTML Less control over rendered HTML. Full control over HTML
State management Automatic state management of controls. Manual state management.
TDD support Weak or custom TDD required. Encourages and includes TDD!

38) How can you display something in CodeIgniter?

Here is a code to display something in CodeIgniter:

<?=$title?>
As opposed to
<?php
echo $title;
?>
Control structures are usually written as follows
<?php foreach ($customers as $customer): ?>
<li>
<p><?=$customer->first_name?><p>
</li>
<?php endforeach; ?>

39) Write a code to demonstrate Model, View, and Controller in CodeIgniter.

Here is a code to demonstrate Model, View, and Controller in CodeIgniter:

Open the file Welcome.php controller located application/controllers:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {
    public function index()
    {
        $this->load->view('welcome_message');
    }
}

Update the index as follows:

public function index()
    {
            $this->load->model('customers_model');

            $data['customer'] = $this->customers_model->get_customer(3);

            $this->load->view('welcome_message',$data);
    }

Write the following code in customer_model.php in application/models.

<?php
class Customers_model extends CI_Model {
    public function get_customer($id) {
        $data['id'] = 3;
        $data['first_name'] = 'John';
        $data['last_name'] = 'Doe';
        $data['address'] = 'Kingstone';

        return $data;
    }
}

Open welcome_message.php located in

application/views/welcome_message.php

Replace the code with the following

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CodeIgniter MVC Basics</title>
</head>
<body>
    <h3>Customer Details Card</h3>

    <p>Customer ID : <strong><?=$customer['id']?></strong></p>
    <p>First Name  : <strong><?=$customer['first_name']?></strong></p>
    <p>Last Name   : <strong><?=$customer['last_name']?></strong></p>
    <p>Address     : <strong><?=$customer['address']?></strong></p>
</body>
</html>

40) Can you create a web application with both webforms and MVC?

Yes. You need to include the below MVC assembly references in the web forms application to create a hybrid application.

System.Web.Mvc
System.Web.Razor
System.ComponentModel.DataAnnotations

41) How can you assign an alias name for ASP.NET Web API Action?

We can give alias name for Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:

[HttpPost]

[ActionName("SaveStudentInfo")]

public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}

42) What is the main difference between MVC and WebAPI?

Here is the main difference between MVC and WebAPI:

MVC framework is used for developing applications that have a User Interface. For that, views can be used for building a user interface.

WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.

43) How can you ensure that Web API returns JSON data only?

To make Web API serialize the returning object to JSON format and returns JSON data only. For that, you should add the following code in WebApiConfig.cs class in any MVC Web API Project:

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

1
2
3

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"))

44) What is the difference between MVVM and MVC?

Here are the important differences between MVVM and MVC:

MVC MVVM
A Controller is the entry point to the Application. The View is the entry point to the Application.
One to many relationships between Controller & View. One to many relationships between View & View Model.
View does not have reference to the Controller View have references to the View-Model.
MVC is Old Model MVVM is a relatively New Model.
Difficult to read, change, to unit test, and reuse this Model The debugging process will be complicated when we have complex data bindings.
MVC Model component can be tested separately from the user Easy for separate unit testing and code is event-driven.

45) What is MVC in AngularJS?

Angular.js follows the MVC architecture, the diagram of the MVC framework is shown below.

  • The Controller represents the layer that has the business logic. User events trigger the functions which are stored inside your controller. The user events are part of the controller.
  • Views are used to represent the presentation layer which is provided to the end-users.
  • Models are used to represent your data. The data in your model can be as simple as just having primitive declarations. For example, if you are maintaining a student application, your data model could just have a student id and a name. Or it can also be complex by having a structured data model. If you are maintaining a car ownership application, you can have structures to define the vehicle itself in terms of its engine capacity, seating capacity, etc.

46) What is the role of MVC in AngularJS?

Following is a simple definition of the working of AngularJS Controller.

  • The controller’s primary responsibility is to control the data which gets passed to the view. The scope and the view have two-way communication.
  • The properties of the view can call “functions” on the scope. Moreover, events on the view can call “methods” on the scope. The below code snippet gives a simple example of a function.
    • The function($scope) which is defined when defining the controller and an internal function which is used to return the concatenation of the $scope.firstName and $scope.lastName.
    • In AngularJS when you define a function as a variable, it is known as a Method.

  • Data in this way pass from the controller to the scope, and then the data passes back and forth from the scope to the view.
  • The scope is used to expose the model to the view. The model can be modified via methods defined in the scope, which could be triggered via events from the view. We can define two-way model binding from the scope to the model.
  • Controllers should not ideally be used for manipulating the DOM. This should be done by the directives, which we will see later on.
  • The best practice is to have controllers based on functionality. For example, if you have a form for input and you need a controller for that, create a controller called “form controller”.

47) How to build a basic Controller in AngularJS

The below code snippet is a simple HTML page that has the title of “Event Registration” and has references to important libraries such as Bootstrap, jquery, and Angular.

  1. We are adding references to the bootstrap CSS stylesheets, which will be used in conjunction with the bootstrap libraries.
  2. We are adding references to the AngularJS libraries. So now, whatever we do with angular.js going forward will be referenced from this library.
  3. We are adding references to the bootstrap library to make our web page more responsive for certain controls.
  4. We have added references to jquery libraries which will be used for DOM manipulation. This is required by Angular because some of the functionality in Angular is dependent on this library.

By default the above code snippet will be present in all of our examples so that we can show just the specific angularJS code in the subsequent sections.

Secondly, let’s look at our files and file structure which we are going to start with our course:

  1. First, we segregate our files into 2 folders as is done with any conventional web application. We have the “CSS” folder. It will contain all our cascading style sheet files, and then we will have our “lib” folder, which will have all our JavaScript files.
  2. The bootstrap.css file is placed in the CSS folder, and it is used for adding a good look and feel for our website.
  3. The angular.js is our main file which was downloaded from the angularJS site and kept in our lib folder.
  4. The app.js file will contain our code for the controllers.
  5. The bootstrap.js file is used to supplement the bootstrap.cs file to add bootstrap functionality to our web application.
  6. The jquery file will be used to add DOM manipulation functionality to our site.

Example of using angular.js:

What we want to do here is just to display the words “AngularJS” in both text format and in a text box when the page is viewed in the browser.

<!DOCTYPE html>
<html>
<head>
    <meta chrset="UTF 8">
    <link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body>
<h3> Guru99 Global Event</h3>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<script src="lib/angular.js"></script>
<script src="lib/bootstrap.js"></script>
<script src="lib/jquery-1.11.3.min.js"></script>

<div ng-app="DemoApp" ng-controller="DemoController">

    Tutorial Name : <input type="text" ng-model="tutorialName"><br>

    This tutorial is {{tutorialName}}
</div>
<script>
    var app = angular.module('DemoApp',[]);

    app.controller('DemoController', function($scope){
    $scope.tutorialName = "Angular JS";
    });
</script>

</body>
</html>

48) What is the use of ng-controller in external files in AngularJS

Perform the following steps to use ng-controller in External Files in AngularJS

Step 1) In the app.js file, add the following code for your controller

angular.module('app',[]).controller('HelloWorldCtrl',function($scope)
{
    $scope.message = "Hello World"
});

Step 2) Now, in your Sample.html file, add a div class that will contain the ng-controller directive and then add a reference to the member variable “message.”

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta chrset="UTF 8">
    <title>Event Registration</title>
    <link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body>
<h3> Guru99 Global Event</h3>
<div class="container">
    <div ng-controller="HelloWorldCtrl">{{message}}</div>
</div>

<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<script src="lib/angular.js"></script>
<script src="lib/bootstrap.js"></script>
<script src="lib/jquery-1.11.3.min.js"></script>

<script src="app.js"></script>

</body>
</html>

49) Write code to define methods in AngularJS Controller?

Here is a code to define methods in AngularJS Controller:

<!DOCTYPE html>
<html>
<head>
    <meta chrset="UTF 8">
    <title>Event Registration</title>
    <link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body ng-app="DemoApp">
<h3> Guru99 Global Event</h3>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<script src="lib/angular.js"></script>
<script src="lib/bootstrap.js"></script>
<script src="lib/jquery-1.11.3.min.js"></script>

<div ng-app="DemoApp" ng-controller="DemoController">
    Tutorial Name :<input type="text" ng-model="tutorialName"><br>
    <br>
    This tutorial is {{tutorialName}}    
</div>

<script>
var app = angular.module('DemoApp', []);
app.controller('DemoController', function($scope) {
    $scope.tutorialName = "Angular JS";
    $scope.tName = function() {
        return $scope.tName;
    };
});
</script>    
</body>
</html>

50) Write code using ng-model to display multi-line input control in AngularJS.

Here is a code using ng-model to display multi-line input control in AngularJS:

<!DOCTYPE html>
<html>
<head>
    <meta chrset="UTF 8">
    <title>Event Registration</title>
    <link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body >
<h3> Guru99 Global Event</h3>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>

<div ng-app="DemoApp" ng-controller="DemoCtrl">
    <form>
        &nbsp;&nbsp;&nbsp;Topic Description:<br> <br>
        &nbsp;&nbsp;&nbsp;
    <textarea rows="4" cols="50" ng-model="pDescription"></textarea><br><br> 
    </form>
</div>

<script>
    var app = angular.module('DemoApp',[]);
    app.controller('DemoCtrl', function($scope){
        $scope.pDescription="This topic looks at how Angular JS works \nModels in Angular JS"});
</script>

</body>
</html>

51) Write code to demonstrate the use of input elements.

Here is a code example using AngulaJS input elements:

<!DOCTYPE html>
<html>
<head>
    <meta chrset="UTF 8">
    <title>Event Registration</title>
    <link rel="stylesheet" href="css/bootstrap.css"/>
    <script src="https://code.angularjs.org/1.6.9/angular.js"></script>
</head>
<body >
<h3> Guru99 Global Event</h3>

<div ng-app="DemoApp" ng-controller="DemoCtrl">
    <form>
        &nbsp;&nbsp;&nbsp;Topic Description:<br> <br>
        &nbsp;&nbsp;&nbsp;
         
        Name : <input type="text" ng-model="pname"><br>
        &nbsp;&nbsp;&nbsp;
        Topic : <br>&nbsp;&nbsp;&nbsp;
        <input type="checkbox" ng-model="Topic.Controller">Controller<br>&nbsp;&nbsp;&nbsp;
        <input type="checkbox" ng-model="Topic.Models">Models
    </form>
    </div>

<script>
    var app = angular.module('DemoApp',[]);
    app.controller('DemoCtrl', function($scope){
        $scope.pname="Guru99";
         
        $scope.Topic =
        {
            Controller:true,
            Models:false
        };     });
</script>

</body>
</html>

52) How can you create a model in PHP?

Here is a code to create model in PHP:

<?php 
class Opinion_poll_model extends CI_Model 
{ 
    public function __construct() 
    { 
        $this->load->database(); 
    } 

    public function total_votes() 
    { 
        $query = $this->db->select('COUNT(choice) as choices_count')->get('js_libraries');
        return $query->row()->choices_count; 
    } 

    public function get_results() 
    { 
        $libraries = array("", "JQuery", "MooTools", "YUI Library", "Glow"); 
        $table_rows = ''; 

        for ($i = 1; $i < 5; $i++) 
        {
             $sql_stmt = "SELECT COUNT(choice) choices_count FROM js_libraries WHERE choice = $i;"; 
             $result = $model->

             select($sql_stmt); $table_rows .= "<tr><td>" . $ libraries [$i] . " Got:</td><td><b>" . $result[0] . "</b> votes</td></tr>"; 
        } 
        public function add_vote($choice) 
        { 
            $ts = date("Y-m-d H:i:s"); $data = array('choice' => $choice, 'ts' => $ts); $this->db->insert('js_libraries', $data); 
        } 
   } 
?>

53) Why use PHP MVC Framework?

You should use PHP MVC Framework because it simplifies working with complex technologies by:

  • Hiding all the complex implementation details
  • Providing standard methods that we can use to build our applications.
  • Increased developer productivity, this is because the base implementation of activities such as connecting to the database, sanitizing user input, etc., are already partially implemented.
  • Adherence to professional coding standards

54) What are popular PHP MVC frameworks?

Here are popular PHP MVC frameworks:

CodeIgniter: It is one of the most popular PHP MVC frameworks. It’s lightweight and has a short learning curve. It has a rich set of libraries that help build websites and applications rapidly. Users with limited knowledge of OOP programming can also use it.

Kohana: It’s a Hierarchical Model View Controller HMVC that is a secure and lightweight framework. It has a rich set of components for developing applications rapidly.

CakePHP: It is modeled after Ruby on rails. It’s known for concepts such as software design patterns, convention over configuration, ActiveRecord, etc.

Zend: It is a powerful framework that is;

  • Secure, reliable, fast, and scalable
  • Supports Web 2.0 and creation of web services.

It features APIs from vendors like Amazon, Google, Flickr, Yahoo, etc. It’s ideal for developing business applications.

55) How can you create views in PHP?

Here is a code to create views in PHP:

opinion_poll_form.php 
<html>
<head>
    <title>
        JavaScript Libraries - Opinion Poll
    </title>
</head>

<body>
    <h3>JavaScript Libraries - Opinion Poll</h3>
    <p><b>What is your favorite JavaScript Library? </b></p>
    <form method="POST" action="index.php">
        <p>
            <input type="radio" name="vote" value="1" /> JQuery
            <br />
            <input type="radio" name="vote" value="2" /> MooTools
            <br />
            <input type="radio" name="vote" value="3" /> YUI Library
            <br />
            <input type="radio" name="vote" value="4" /> Glow </p>
        <p>
            <input type="submit" name="submitbutton" value="OK" />
        </p>
    </form>
</body>
</html>

Let’s now create the results page results.php

<html>
    <head>
        <title>JavaScript Libraries - Opinion Poll Results</title>
    </head>
    <body>

        <h3>JavaScript Libraries - Opinion Poll Results</h3>

        <p><b>What is your favorite JavaScript Library?</b></p>

        <p><b><?php echo $total_votes; ?></b> people have thus far taken part in this poll:</p>

        <p><table><tr><td>

            <?php print($rows); ?>

        </tr></td></table></p>

        <p><a href="">Return to voting page</a></p>
</body>
</html>

Free PDF Download: MVC Interview Questions & Answers