Interview Questions (Click on Question to view the answer)

Q 1 : What are the different ways to recieve data from view to controller?

We have several ways through which we can pass data from a view to controller.

1.Strongly Typed Model

This is one of the very common approach which we use in MVC. we can directly receive form values through a model in controller. In this approach we bind a view directly from a model and when we post the form we can receive all the form data in a object of that model as a parameter in the post action method.

Example : Suppose i have a StudentModel in my project as below

 public class StudentModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string PhoneNo { get; set; }
        public string Address { get; set; }
    }
I have a controller named StudentController where i have a action method named StudentRegistration with HttpGet verb as below

  public class StudentController : Controller
    {
        [HttpGet]
        public ActionResult StudentRegistration()
        {
            return View();
        }
    }
While creating a view i am selecting strongly Typed view as below


Once we will click on add we will get a view inside Views/Student Folder named StudentRegistration.cshtml

Now create another action method with httpPost verb where we will post our form as below

 public class StudentController : Controller
    {
        [HttpGet]
        public ActionResult StudentRegistration()
        {
            return View();
        }

        [HttpPost]
        public ActionResult StudentRegistration(StudentModel sm)
        {
            return View();
        }
    }
Now fill the form click on submit button we will get all the values in StudentModel object named sm as below



2.Request Object

Suppose we dont want to use Strongly type Model and we are creating our view without the help of the Model. Suppose if we are creating our StudentRegistration view as below then we will not be able to recieve post data in model Object. In that case we need to choose a different approach to get the post data in action method.



We created a Action Method named StudentReg where we will post the form and there we can recieve the form post data through Request object as below

    public class StudentController : Controller
    {
        [HttpGet]
        public ActionResult StudentRegistration()
        {
            return View();
        }

        [HttpPost]
        public ActionResult StudentReg()
        {
            string name = Request["txtName"].ToString();
            string email = Request["txtEmail"].ToString();
            string phoneNo = Request["txtPhoneNo"].ToString();
            string password = Request["txtPassword"].ToString();
            return View();
        }

    }

3.Form Collection

This is another way to get the post data in controller. We can get the post data through Form collection as well. Suppose we have a view as in above example and we want to get all the post data in Controller then we will use Form Collection as below
    public class StudentController : Controller
    {
        [HttpGet]
        public ActionResult StudentRegistration()
        {
            return View();
        }
        [HttpPost]
        public ActionResult StudentReg(FormCollection col)
        {
            string name = col["txtName"].ToString();
            string email = col["txtEmail"].ToString();
            string phoneNo = col["txtPhoneNo"].ToString();
            string password = col["txtPassword"].ToString();
            return View();
        }
    }

4.Through Parameters

We can recieve post data directly in parameters of a Action Method . Parameter Name should be same the id of a control for example if Id of a text box on a view is txtName then Parameter name should be txtName. Here is an example

  public class StudentController : Controller
    {
        [HttpGet]
        public ActionResult StudentRegistration()
        {
            return View();
        }
        [HttpPost]
        public ActionResult StudentReg(string txtName,string txtEmail,string txtPhoneNo,string txtPassword)
        {
            return View();
        }
    }
On StudentRegistration View we have Name,Email,PhoneNo and Password text boxes having id txtName,txtEmail,txtPhoneNo and txtPassword

Note : Control ID should be same but we can pass parameters in any order. ie. we can write txtEmail first before txtName.

Q 2 : What are the different ways to pass multiple model from controller to view?

In MVC we cannot use multiple model tag on a view. But Many times we need to pass multiple models from controller to view or we want to show data from multiple model on a view. For example we want to show a Blog and List of Comments of this Blog on a Single View or suppose if we want to show a Category and List Of Products related to this category on a View. So in such situations we need to pass multiple models to a Single View and we know in MVC , View does not accept more than one model. We have many solution of this problem.

Different ways to achieve

In this article i will discuss 10 ways to bind multiple models on a Single view

1. View Model

2. View Bag

3. View Data

4. Temp Data

5. Session

6. Dynamic

7. Tuples

8. Render Action

9. JSON

10. Navigation Propeties

We will see all these approaches with the help of an example.Suppose we have a Senerio where We want to display a Blog and List of Comments on a view. We will see different ways to achieve this .

Below are the main players of this Example

1. Blog Model
2. Comment Model
3. GetBlog() : In this method where i will create dummy data for Blog.
4. GetComments() : In this method where i will create dummy data for comments.
5. A Controller (I will name it BlogCommentCotroller)
6. View

I created a project named MultipleModels and now i will create all the required elements before starting different approaches.

1. Blog Model :- Create a Model named BlogModel in your project . Right click on Models Folder and add a class . I created below BlogModel class in Models folder.

  public class BlogModel
    {
        public int BlogID { get; set; }
        public string BlogTitle { get; set; }
        public string BlogDescription { get; set; }
        public DateTime CreatedDate { get; set; }

    }
2. Comment Model :- Right click on Models folder and add another class named CommentModel as below

  public class CommentModel
    {
        public int CommentID { get; set; }
        public string Comment { get; set; }
        public string CommentedBy { get; set; }
        public int BlogID { get; set; }
    }

1. View Model

iewModel is a class which contains the properties which are represented in view. represents the data that you want to display on your view/page. View model a is simple class which can contain more than one class property. Suppose if we want to create a View where we want to display a Blog and List of Comments then we will create our View Model (BlogCommentViewModel.cs) as below

Create a folder named ViewModel in your project and right click on that folder and create a class file named "BlogCommentViewModel.cs"

   public class BlogCommentViewModel
    {
        public BlogModel Blog { get; set; }

        public List<CommentModel> Comments { get; set; }
    }
In above ViewModel (BlogCommentViewModel) we created a property named Blog of BlogModel Type becuase we want to display a single Blog Detail on our View/Page and a second property named Comments of List of CommentModel type becuse we want to display the list of comments associated to the Blog.

Note : We can place the viewmodel (BlogCommentViewModel) in any folder in our project but i created a folder named ViewModel where i will place all the viewmodels created for this project.

Its time to create a controller named BlogController and create a action method inside named GetBlogComment as below

 public class BlogController : Controller
    {
        public ActionResult GetBlogComment()
        {
            return View();
        }
    }
Now first we will create a object of view Model and will set Blog and Comments propeties as below. I created two functions for Blog and Comment dummy data.

    public class BlogController : Controller
    {
        public ActionResult GetBlogComment()
        {
            BlogCommentViewModel BCVM = new BlogCommentViewModel();
            BCVM.Blog = GetBlogModel();
            BCVM.Comments = GetCommentModel();
            return View(BCVM);
        }

        public BlogModel GetBlogModel()
        {
           BlogModel bModel = new BlogModel() { BlogID = 1,
                                                BlogTitle = "MVC Blog", 
                                                BlogDescription = "This is MVC Blog", 
                                                CreatedDate = DateTime.Now };
            return bModel;
        }

        public List GetCommentModel()
        {
            List cModel = new List();

            cModel.Add(new CommentModel() { BlogID = 1, CommentID = 1, Comment = "Good One", CommentedBy = "Vijay" });
            cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Nice", CommentedBy = "Nishant" });
            cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Perfect", CommentedBy = "Saurabh" });
            return cModel;
        }
    }
Note : Don't forget to add Models and ViewModels namespaces.

Now right click on GetBlogComment() action method and select Add View and while creating view select "Create a Strongly-Typed view" and select your view model named 'BlogCommentViewModel' and select "empty"" in scaffold Template as below



Now double click on your view (GetBlogComment.cshtml) and create your view as below



I added some table css also in Style.css

table, td, th {
        border: 1px solid #ddd;
        text-align: left;
    }
    table {
        border-collapse: collapse;
        width: 100%;
    }
    th, td {
        padding: 15px;
    }
Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below

2. View Bag

We use view Bag to pass data from controller to view.ViewBag use the property that takes advantage of the new dynamic features in C# 4.0.There is no typecasting needed in case of ViewBag. So we can take help of ViewBag to pass multiple data from controller to View. ViewBag is a property of ControllerBase class.View Bag scope is only during the current request.To pass multiple model we will create two view bag in our action method as below.

  public ActionResult GetBlogComment()
        {
            ViewBag.Blog = GetBlogModel();
            ViewBag.Comments = GetCommentModel();
            return View();
        }
Now change your view (GetBlogComment.cshtml) according to view Bag as below



Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below

3. View Data

ViewData is used to pass data from controller to view.View Data scoper is only during the current request.View Data needs typecasting for getting data.ViewData is a property of ControllerBase class.ViewData is a derivative of the ViewDataDictionary class, so we can access with “key/value”

To use the ViewData for multiple models change your action method as below

  public ActionResult GetBlogComment()
        {
            ViewData["Blog"] = GetBlogModel();
            ViewData["Comments"] = GetCommentModel();

            return View();
        }
Now change your view (GetBlogComment.cshtml) according to view Data as below



Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below

4. Temp Data

TempData is also a dictionary derivative from TempDataDictionary class. TempData stored in short lives session. We can pass multiple models through TempData also.

Change your action method as below

  public ActionResult GetBlogComment()
        {
            TempData["Blog"] = GetBlogModel();
            TempData["Comments"] = GetCommentModel();

            return View();
        }
Now change your view (GetBlogComment.cshtml) according to Temp Data as below



Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below

5. Session

Session is used to pass data across controllers in MVC Application.Session data never expires (by default session expiration time is 20 minutes but it can be increased).Session is valid for all requests, not for a single redirect.

For Session, Change your action Method as below

   public ActionResult GetBlogComment()
        {
            Session["Blog"] = GetBlogModel();
            Session["Comments"] = GetCommentModel();

            return View();
        }
Now change your view (GetBlogComment.cshtml) according to Session as below

Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below

6. Dynamic (ExpandoObject)

The ExpandoObject class enables us to add and delete members at run time.So If we want to build up an object to work with on the fly at runtime then we can use Expando Object.

I am not going in detail about ExpandoObject. let's see how can we use Expando with Multiple Models.

Change the action method as below

   public ActionResult GetBlogComment()
        {         
            dynamic BCVM = new ExpandoObject();
            BCVM.Blog = GetBlogModel();
            BCVM.Comments = GetCommentModel();
            return View(BCVM);
        }
Note :To use ExpandoObject Add System.Dynamic Namespace.

Change your view as below



Run the application and you will get the same output.

7. Tuples

Tuple is an ordered sequence, immutable, fixed-size and of heterogeneous objects. each object in tuple is being of a specific type.

Tuples are not new in programming. They are already used in F#, Python and databases. They are new to C#. The tuples were introduced in C# 4.0 with dynamic programming.

we can use Tuples also to pass multiple models to view as below

   public ActionResult GetBlogComment()
        {
            var BCVM = new Tuple<BlogModel, List<CommentModel>>(GetBlogModel(), GetCommentModel());
            return View(BCVM);
        }
And now our view will looks like



Now run the project and we will get the expected output.

8. Render Action

Render actions are special controller methods defined only to be called from view. We create Render Action Method same as we create regular Action Method.

A Render action is a public method on the controller class. Rener Action is called from view not from URL so we should decorate RenderAction with the [ChildActionOnly] attribute.

I am creating two Action Methods from where i will return partial view Results and will render those results on view using RenderAction Methods.

  public ActionResult GetBlogComment()
        {
            return View();
        }

        public PartialViewResult RenderBlog()
        {
            return PartialView(GetBlogModel());
        }

        public PartialViewResult RenderComments()
        {
            return PartialView(GetCommentModel());
        }
Right click on RenderBlog() and add a view as below (Make sure we need to create a partial view so check that opetion)



Now change the code of your created partial(RenderBlog.cshtml) view as below



Same way right click on RenderComments and create another partial view as below



change this partial view(RenderComments.cshtml) as below



Its time to render these two partial view on our main view named GetBlogComment.cshtml.



Now run the project and we will get the expected output.

9. JSON

We can Bind Multiple Models with the help of Json as well. We will retun JsonResult from action Method and on View through JQuery we can pasrse the JSON data and Bind on View. Here is the code

Change your action method so that Action Method can return the JSON

   public ActionResult GetBlogComment()
        {
            return View();
        }

        public JsonResult RenderBlog()
        {
            return Json(GetBlogModel());
        }

        public JsonResult RenderComments()
        {
            return Json(GetCommentModel());
        }
Chanage your view as below




Hit F5 and we will get the required result.

10. Navigation Properties

If we have two related models then we can bind a model into another model as a property and can pass to a View. For example we have a Blog Model and Comment Model and A blog can contains multiple comments so we can declare a Navigation Propery in Blog Model as below

  public class BlogModel
    {
        public int BlogID { get; set; }
        public string BlogTitle { get; set; }
        public string BlogDescription { get; set; }
        public DateTime CreatedDate { get; set; }

        public List<CommentModel> Comments { get; set; } //Navigation Property

    }
Now change your GetBlogModel() function and GetBlogComment() Action as below

   public ActionResult GetBlogComment()
        {
            BlogModel BM = GetBlogModel();
            return View(BM);
        }

        public BlogModel GetBlogModel()
        {
            BlogModel bModel = new BlogModel()
            {
                BlogID = 1,
                BlogTitle = "MVC Blog",
                BlogDescription = "This is MVC Blog",
                CreatedDate = DateTime.Now,
                Comments = GetCommentModel() //Add Comments here
            };
            return bModel;
        }

        public List<CommentModel> GetCommentModel()
        {
            List<CommentModel> cModel = new List<CommentModel>();

            cModel.Add(new CommentModel() { BlogID = 1, CommentID = 1, Comment = "Good One", CommentedBy = "Vijay" });
            cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Nice", CommentedBy = "Nishant" });
            cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Perfect", CommentedBy = "Saurabh" });
            return cModel;
        }
Now create your view as below



Q 3 :Difference between RedirectToAction() and RedirectToActionPermanent()?

We use RedirectPermanent() method if the resource has been moved permanently and will no longer be accessible in its previous location. Most browsers will cache this response and perform the redirect automatically without requesting the original resource again.
We use Redirect() Method if the resource may be available in the same location (URL) in the future.
Suppose we have students in our system. We also have an option to delete existing students. In Application we have a resource /Student/{StudentId} that displays the details of a given student. If the Student has been deleted, We must redirect to the /Student/does-not-exist page. In this case:
If the student will never be restored again, we should use RedirectPermanent so the browser can go directly to /Student/does-not-exist in subsequent requests even if the URL points to /Student/{StudentID}.
If the Student may be un-deleted sometime in the future, we should use a regular Redirect.
Here is an Example
Suppose we have a Student Controller and a Two Actions Method As below
public class StudentController : Controller
	{
		public ActionResult Index(int id)
		{
			return RedirectToAction("DoesNotExist");
		}
		public ActionResult DoesNotExist()
		{
			return View();
		}
	}
Here if we use RedirectToAction Method for Student/Index/1 then first it will call the Index Method and then redirect to DoesNotExist() Method.If we will call again then it will hit again Index() Method and then DoesNotExist() Method.
public class StudentController : Controller
	{
		public ActionResult Index(int id)
		{
			return RedirectToActionPermanent("DoesNotExist");
		}
		public ActionResult DoesNotExist()
		{
			return View();
		}
	}
But if we use RedirectToActionPermanentMethod() for Student/Index/1 first it will call the Index Method and then redirect to DoesNotExist() Method but If we will call again then it will call directly DoesNotExist() Method.

Q 4 :Status Code of RedirectToActionPermanent() Method?

Ans : 301

Q 5 :Status Code of RedirectToAction() Method?

Ans : 302

Q 6 :In an ASP .Net MVC Application, browsers requests are mapped to?
1. Pages
2. Controller
3. Model
4. All of the above
5. None of the above

Ans : 2 (Controller)

Q 7 :Which method marks the specified key in a TempData dictionary for retention?
1. TempData.Revive()
2. TempData.Alive()
3. TempData.Increase()
4. TempData.Load()
5. TempData.Store()
6. TempData.Keep()

Ans : 6 (TempData.Keep())

Q 8 :Can you point your browser to a view and have it render?
1. Yes
2. No

Ans : 2 (No)

Q 9 :Which of the below are return types of a controller action method?
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. All the above

Ans : 5 ( All the above)

Q 10 :What is the difference between ActionResult and ViewResult?

Ans : ActionResult" is an abstract class while "ViewResult" derives from "ActionResult" class.ActionResult" has several derived classes as below
1. ViewResult - Renders a specified view to the response stream
2. PartialViewResult - Renders a particular partial view to the response stream
3. EmptyResult - An empty response is given.
4. RedirectResult - It Performs an HTTP redirect to a specified URL
5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is decide by the routing engine, based on given data from route.
6. JsonResult - Serializes a given View Data object to JSON format
7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8. ContentResult - its Write content to response stream without need of a view
9. FileContentResult - Returns a file to the client
10. FileStreamResult - it Returns a file to the user, that is provided through a Stream
11. FilePathResult - it Returns a file to the user

Q 11 :What is ViewResult() ?
A. Abstract Class
B. Concrete Class
C. Both A and B
D. None

Ans : B :- ActionResult" is an abstract class while "ViewResult" derives from "ActionResult" class.So ViewResult class is a Concrete Class.

About Company

TechiesEra is a quality Training Center of Noida.TechiesEra provides summer training in Noida on Hadoop, MongoDB,CouchDB,NoSql,Dot Net, Android, Java,PHP etc with live projects. TechiesEra is group of highly qualified professionals in the field of IT education & recruitments.

Get in Touch

  • Phone:
    +91-9560231801
  • Email:
    info@TechiesEra.com
  • Address:
    C-33,Sector - 2
    Near By : Nirula Hotel
    Noida -201301