First 31 ASP.NET MVC Interview Questions and Answers for the year - 2023 - USMTECHWORLD.

1. How to set default route to an Area in ASP.NET MVC?

Answer:
You need to add DataToken to Default Route, in order to make your area as default route in route.config. for eg:- You have seperate area for login related files and want to be your default route during your application startup.

              routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { area= "Login", controller = "Login", action = "Index", id = UrlParameter.Optional }
            ).DataTokens.Add("area","Login");

2.What are the return types of controller action methods?

Answer:

3.What are Filters in MVC?

Answer:
In MVC,sometimes we need to perform action before or after particular method or operation. Types of Filters:

4.What are action filters?

Answer:
These are special attributes which can be applied to either a controller or action methods.It can be executed before and after controller action executes.

5.What are different types of action filters?

Answer:

6.What is Authorize? Give an example.?

Answer:
It allows only authorize users to login to the application. For non authorized user , it goes to login page.

    
        [Authorize]
        public ActionResult Index()
        {
        ViewBag.Message = "This page is viewed only by authorized user";
        return View();
        }

    

7.What is Routing? What are the 3 segments of Routing?

Answer:
Routing helps you to define the URL structure and map the URL with the controller.Routing happens on the basis of URL pattern
The 3 segments of routing are:
Controller name
Action method name
Parameter
Please see in Route.config file of your mvc application.

8.How can we maintain session in ASP.NET MVC?

Answer:
SESSION can be maintained in MVC in 3 ways.

9.What is Viewdata?

Answer:
It is useful for transfering data from controller to view.it is again a keyvalue pair.

10.What is ViewBag?

Answer:
Viewbag is useful when you want to transfer data from controller to view.The viewbag is dynamic property of controllerbase class

11.What is Tempdata?

Answer:
It is again a key value pair.It is used when data is to be used in two subsequent request.It can be between 2 actions or 2 controllers.You cant get the tempdate value in 3 rd request,

12.What is the advantages of ASP.NET MVC?

Answer:
It is MVC based development model
It has partial views.
It has no viewstate.
It has HTML helpers.
The main advantage of ASP.NET MVC is "Seperation of Concerns".The model does not know about the View.
The View does not know about the Controller.
This makes MVC application easier to test and maintain.
ASP.NET MVC does not use data controls like GridView, Repeater.
Large projects makes use of ASP.NET MVC.

13.What is ViewModel in ASP.NET MVC?

Answer:
It is used to display more than one model on View.
Suppose we want to display both student entity and Marks entity
under one single entity(StudentMarks) then we can call directly from this single entity.

14.What is RenderSection in ASP.NET MVC?

Answer:
@RenderSection("featured", required: false)
The first parameter “featured” tells that the name of the section that we want to render in browser.
The second parameter ‘false’ tells that whether the section ‘featured’ is wanted or not.
If it is ‘true’ and not implemented then app will throw error.

15.What is RenderBody in ASP.NET MVC?

Answer:
Renderbody must be contained within layout page.
It renders all the content of child views.
Multiple renderbody is not allowed in layout page.
"@RenderBody" is used to inject content from child page to master page design (Layoutpage).

16.HOW PHOTO IS RETRIEVED FROM DATABASE TO WEBPAGE?

Answer:
in table they are storing image as byte[] so during retrieval in webapplication //storing photo byte in local byte[] dbbyte = (byte[])ds.Tables[0].Rows[0]["Photo"]; //in filepath they are storing like this,
"D:\UploadImages\Student_50161.jpeg"
string filepath = Server.MapPath("~\\UploadImages\\" + "Student_" + ds.Tables[0].Rows[0]["ApplicantID"].ToString() + "." + ds.Tables[0].Rows[0]["FileExtension"].ToString());
then they are writing the byte array got from database to filepath like the below(i.e write the byte array to filestream)

          FS = new FileStream(filepath, System.IO.FileMode.Create);
        FS.Write(dbbyte, 0, dbbyte.Length);
        FS.Close();
finally showing in imageurl which is in webapplication like this
            imgStudentImage.ImageUrl = "~\\UploadImages\\" + "Student_" + ds.Tables[0].Rows[0]["ApplicantID"].ToString() + "." + ds.Tables[0].Rows[0]["FileExtension"].ToString();

17.How documents like image or word or pdf is stored inside the database?

Answer:

             if (FileUpload_DOBDoc.HasFile == true)
                    {
                        personalentity.IsFileUploadModified = true;
                        int length = FileUpload_DOBDoc.PostedFile.ContentLength;
                        byte[] file = new byte[length];
                                    FileUpload_DOBDoc.PostedFile.InputStream.Read(file, 0, length);
                                    personalentity.dobContent = file;
                                    personalentity.dobFileName = Path.GetFileName(FileUpload_DOBDoc.PostedFile.FileName);
                                    personalentity.dobfiletype = FileUpload_DOBDoc.PostedFile.ContentType;
                    }
 ds = BALpersonalentity.InsertDOBDocuments(personalentity);

18.How ASP.NET or ASP.NET MVC talk to WebAPI?

Answer:
The ASP.NET or ASP.NET MVC will talk to WEBAPI through Jquery Ajax.The most used functionality in WebAPI is to fetch data from database and post data into database.To Fetch data from database through WebAPI, we will use GET in Jquery Ajax and remember for getting data dont pass input parameters through data in Ajax.Instead pass input parameters through querystring for that API.But you can very well pass input parameters through data for POST type in Ajax.The following are the examples for GET and POST. GET:-

    $.ajax({
                        type: "GET",
                        url: "http://localhost:60050/api/SampleAPI/GetStudents/?studentno=" + studentno.toUpperCase(),
                        headers: {
                            'Access-Control-Allow-Origin': '*',
                            'Content-Type': 'application/json'
                        },                     
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (res) {
                            OnAPISuccess(res, studentno)
                        },
                        failure: function (response) {
                            alert(response.d);
                        }
                    });
  
POST:-
    $.ajax({
                        type: "POST",
                        url: "http://localhost:60050/api/SampleAPI/SaveStudents" ,                      
						data: '{studentno: "' + studentno + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (res) {
                            OnAPISuccess(res, studentno)
                        },
                        failure: function (response) {
                            alert(response.d);
                        }
                    });
  
you can also pass data like the below format for post api.
   var data = { studentno: studentnumber.toUpperCase(), apiresult: response };
     $.ajax({
                        type: "POST",
                        url: "http://localhost:60050/api/SampleAPI/SaveStudents" ,                      
						data: data,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (res) {
                            OnAPISuccess(res, studentno)
                        },
                        failure: function (response) {
                            alert(response.d);
                        }
                    });
  

19.How to navigate from one view to another view using actionresult method in ASP.NET MVC?

Answer:
NewUser Page:-

  [httppost]
public ActionResult Save(User usermodel)
{
 ../do dome logic
return RedirectToAction("Index","UserRegistration")
or
return new RedirectToRouteResult(
	new RouteValueDictionary(      
	 new {action="Index",controller="UserRegistration"}));

}

  

20.Different ways to navigate from one page to another page method in asp.net mvc

Answer:
View()- The View() does not make new request instead it renders view without changing the url in the browser bar.

[HttpPost]
public ActionResult Index(string Name)
{
 ViewBag.Message = "Hi, usmtechworld";
 
 return View("secondpage);
}

Redirecttoaction()- It makes new request and URL in the browser bar is updated.

 [HttpPost]
        public ActionResult SaveUser(User usermodel)
        {        
       
            return RedirectToAction("Index", "UserRegistrationList");     
            
        }

Redirect()- it makes new request and URL in the browser bar is updated.

[HttpPost]
public ActionResult Index(string Name)
{
 ViewBag.Message = "Hi,usmtechworld";
  return Redirect("User/MyIndex");
}

Redirectoroute()-it redirects specific routes in the route table.

Public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
 "MyRoute", // Route name
 "Registration/", // URL 
 new { controller = "Registration", action = "Index"} // Parameter defaults
 );
}

[HttpPost]
public ActionResult Index(string Name)
{
 return RedirectToRoute("MyRoute");
}

21.How to pass multiple parameters in PostAsync C#?

Answer:
When you post the data as simple types, say for example you need to pass username and password to your API method

 [Route("users/CheckLogin")]
public IHttpActionResult CheckLogin(string username, string password)

 var value = new Dictionary
 {
    { "username", "usm" },
    { "passwird", "tech123" }
 };

 var content = new FormUrlEncodedContent(value);
 var result = await client.PostAsync("users/checklogin/", content);
 string resultContent = await result.Content.ReadAsStringAsync();
  

The best way is to create model for your multiple parameters and pass that model to your API method like the below code.
  public class LoginModel 
{
    [Required]
    public string Username { get;set }

    [Required]
    public string Password { get;set }
}
  
  [HttpPost]
[Route("users/CheckLogin")]
public IHttpActionResult CheckLogin([FromBody]LoginModel model)
{
   //validate your model    
   if ( model == null || !ModelState.IsValid )     
   {
       return BadRequest();
   }

   //stuff
   return Ok();
}
  

To call this WebAPI in C#,do like the below code.
  var model = new LoginModel { Username = "abc", Password="abc" } ;

using (var client = new HttpClient())
{               
    var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");               

    var result = await client.PostAsync("users/CheckLogin", content);
    return await result.Content.ReadAsStringAsync();
}
  

Tips : DONT SEND PASSWORD TO URL ROUTES LIKE THIS [Route("users/CheckLogin/{username}/{password}")], if you do so your password can be hacked by someone, so be careful when you are sending any sensitive information throug url, instead you can pass username and password in (LoginModel)model class and also make sure that your request is through https.

22.What is generics in C#?

Answer:
Generics means not specific,it is not specific to particular data type.Generics allows you to define classes,methods,interfaces,fields,properties and events with Type parameter.
One of the most significant feature of generics is TypeSafety.Generics is faster than other collections such as arraylist. What is Type Parameter in Generics?
It is specified by using angle bracket(eg:-TypeName<T>) where T is of any type like string,int,float

public class GenericList
{
    public void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();
        list1.Add(1);
        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();
        list2.Add("");
        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
        list3.Add(new ExampleClass());
    }
}

23.What is RouteTable?

Answer:
When MVC application starts, the application start method is called.This method will call RegisterRoutes method.This RegisterRoutes method will create RouteTable.By default this routetable contains default route.This default route consists of 3 segments. First Segment : Controller = Home
Second Segment : Action = Index
Third Segment: ID=parameter named id

24.Where is RouteTable stored in MVC?

Answer:
Routetable is collection of routes that is stored in RouteConfig.cs under App_start folder.

25.How to use multiple models with single View in MVC?

Answer:
There are many ways to use multiple models within the single View.


1.Dynamic Model: ExpandoObject is a class in .netframework4.0 that allows us to dynamically add or remove properties at runtime. Controller snippet:
public class Homecontroller:Controller
{
public ActionResult Index()
{
dynamic objmodel=new ExpandoObject();
objmodel.Teachers=getteachers();
objmodel.Students=getStudents();
return View(objmodel);
}
}
View Snippet:
@using dynamicmodelinview
@model dynamic
@foreach(Teacher teach in Model.Teachers)
{
@teach.TeacherName;
@teach.TeacherID;
}

@foreach(Students stud in Model.Students)
{
@stud.Studentid;
@stud.Studentname;
}
2.USING VIEW MODEL
This is a single class which consists of multiple models.It contains multiple models as a property.
public class ViewModelMultiple
{
public Ienumerable<Teacher> Teachers{get;set;}
public Ienumerable<Student> Students{get;set;}
Controller Snippet:
public ActionResult Index() { ViewModelMultiple objmultiplemodels=new ViewModelMultiple(); objmultiplemodels.Teachers=GetTeachers(); objmultiplemodels.Students=GetStudents(); return View(objmultiplemodels); }
View Snippet:
@using viewmodelsexample
@model ViewModelMultiple
 @foreach(Teacher teach in Model.Teachers)
{
@teach.TeacherName;
@teach.TeacherID;
}
@foreach(Students stud in Model.Students)
{
@stud.Studentid;
@stud.Studentname;
}

3.USING VIEWDATA
ViewData is used to transfer data from Controller to View. Controller Snippet:
public ActionResult Index()
{
ViewData["teachers"]=GetTeachers();
ViewData["students"]=GetStudents();
return View();
}
View Snippet:
@using viewdataexample
@{

Ienumerable<Teachers> teachers= ViewData["teachers"] as Ienumerable<Teachers>
 Ienumerable<Students> students= ViewData["students"] as Ienumerable<Students>

}
            @foreach(Teacher teach in Teachers)
{
@teach.TeacherName;
@teach.TeacherID;
}
@foreach(Students stud in Students)
{
@stud.Studentid;
@stud.Studentname;
}
3.USING VIEWBAG
ViewBag also similar to ViewData and it is also used to transfer data from controller to View. ViewBag is dynamic property,
Controller Snippet:
public ActionResult IndexViewBagexanple()
{
ViewBag.Message = "Welcome to my demo!";
ViewBag.Teachers = GetTeachers();
ViewBag.Students = GetStudents();
return View();
}
View Snippet:
@foreach (Teacher teacher in ViewBag.Teachers)
{

@teacher.TeacherId
@teacher.Code
@teacher.Name>

}

4.USING TUPLE
Using tuple object we can pass models from controller to view.The .netframework supports tuple upto seven elements. The great use of tuple is to return multiple values from a method. Controller Snippet:
public actionresult Tupleexample()
{
var tuplemodel=new Tuple<List>Teacher>,<List>Student>>(GetTeachers(),GetStudents());
return View(tuplemodel);
}

View snippet:
@model Tuple<List<Teacher>,List<Student>>
@foreach(Teacher teach in Model.Item1)
{
@teach.TeacherName;
@teach.TeacherID;
}
@foreach(Students stud in Model.Item2)
{
@stud.Studentid;
@stud.Studentname;
}

26.How to get the dropdown change text and value in ASP.NET MVC using Jquery??

Answer:
HTML:

           @HTML.DropdownListFor(m=>m.customername,new SelectList(Model.customerlist,"Value","Text"),"select",
new {@class="form-control",id="ddlcustomer"})

Jquery script:
           
$(document).ready(function(){

$("ddlcustomer").on("change",function(){

var selecteddropdownvalue=$("ddlcustomer option:selected").val();
 var selecteddropdowntext = $('#ddlcustomer').find('option:selected').text();
alert("selected dropdownlist Value:" + selecteddropdownvalue);
alert("selected dropdownlist Text:" + selecteddropdowntext);

});

});


27.How to enable Clientside Validation in MVC?

Answer:

<script src="~/Scripts/jquery-1.8.2.min.js"><script>
<script src="~/Scripts/jquery.validate.min.js"><script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"><script>

<appSettings>       
<add key="PreserveLoginUrl" value="true" >
<add key="ClientValidationEnabled" value="true" >
<add key="UnobtrusiveJavaScriptEnabled" value="true" >
<appSettings>

28.What is BIND Attribute in MVC?

Answer:
ASP.NET MVC enables you to specify which properties of a model class you want to bind.The [Bind] proptery specify which property you want to include or exclude during model binding.

[HttpPost]
public ActionResult Edit([Bind(Include = "Custid, Custname")] Customer cst)
{
var name = std.CustomerName;     
            
return RedirectToAction("Index");
}

[HttpPost]
public ActionResult Edit([Bind(Include = "Custothers")] Customer cst)
{
var name = std.CustomerName;     
            
return RedirectToAction("Index");
}

29.What is ASP.NET MVC SELF HOSTING?

Self Hosting provides runtime environment for application to run in any environment say MAC or Linux or Windows.

30.What is ValidateInput in ASP.NET MVC?

By default, html content or codes are not allowed to submit to the server through asp.net MVC pages.This is to prevent Cross Site Scripting attack in MVC,by default it is disabled by ASP.NET MVC. But sometimes we need to send html content or codes to server like send bold text or formatted text to server.In such a case we need to enable in ASP.NET MVC,Just by adding the following line , we can enable html content or codes to submit to the server.

[HttpPost]  
[ValidateInput(false)]  
public string Index(string message)  
{  
return "Your message" + message;  
}  

we can also use AllowHtml attribute to model property.
public class customer  
{  
[AllowHtml]  
public string customername { get; set; }  
}

31.What is HTML.Raw in ASP.NET MVC?

It returns Html Markup without encoding.In general if we pass any HTML as string in Html.Raw,it renders a valid HTML in the browser. for eg:-

             string content="Hello USMTECHWORLD"
            @Html.Raw(content)

output: it bolds the above content and display it in browser.

>>Click here to get Next set of ASP.NET MVC Q&A