.NET/C# Interview Questions Summary Series: ASP.NET MVC [Learn and improve as appropriate]

PS: In the editor’s city, most of the ERP and BPMS systems work based on .NET, and other BS structure systems are basically based on Vue+.NET, and there are few offers developed by MVC for single storage [only for the editor in Boss The data analysis seen on Zhipin], therefore, this chapter can be listed as an appropriate learning and improvement chapter!

1. What is the difference between TempData\ViewBag\ViewData in MVC?

TempData is stored in the Session. Every time the Controller executes a request, it first obtains TempData from the Session, and then clears the Session. After obtaining the TempData data, although it is stored in the internal dictionary object, each entry in the collection After accessing once, it is deleted from the dictionary table. ViewData stores the Key/Value dictionary, and type conversion is required when using it.
ViewBag and ViewData are only valid in the current Action, which is equivalent to View. ViewBag is slower than ViewData. ViewBag stores dynamic type data and does not require type conversion when used.
The values ​​in ViewData and ViewBag can access each other, because the implementation of ViewBag contains ViewData, and ViewData stores Key/Value dictionary, which requires type conversion

2. Explain the mechanism of the MVC framework and the role of each module?

  • The so-called model is the data source that MVC needs to provide, responsible for data access and maintenance.
  • The so-called view is the user interface used to display the data in the model.
  • The so-called controller is used to process user input, responsible for changing the state of the model and selecting the appropriate view to display the data of the model.

3. What is the relationship between ASP.NET and ASP.NET MVC?

ASP.NET MVC is built on the basis of core ASP.NET, as can be seen from the mvc namespace System.Web.Mvc, because System.Web is the core namespace of Asp.NET.
For example, ASP.NET MVC relies on HttpHandler. Regarding how the request enters the controller, it actually uses the HttpHandler
Session, Cookie, Cache, and Application, which are the ASP.NET object storage mechanisms that still need to be used in MVC.
HttpContext , Request, Response, and Server objects can still be used in MVC, and it is easy to get these objects in the form of Intellisense in Controller

4. What are the benefits of MVC for ASP.NET?

  • Provide very clear performance management, like the ui layer, that is, the view, the data layer model and the management layer controller.
  • Unit testing is easier.
  • Improved data model and view reusability.
  • The structure of the code is more optimized.

5. What is razor view engine?

This engine provides data-bound display templates.

 @model MvcStore.Models.Customer
 @{
    
    ViewBag.Title="Get Customers";}
 <div class="cust"><h3><em>@Model.CustomerName</em></h3></div>

6. What is the difference between view bag and view data?

view bag is an extension of view data. After extension, dynamic properties can be created. The benefits of this are:

  1. No type conversion is required.
  2. We can use the dynamic keyword.
  3. But there is a disadvantage that view bag is slower than view data.

7. Explain the sections?

Sections are part of an html page.

 @rendersection("testsection")

In the subpage we define the following sections.

 @section testsection {
    
    
 <h1>test content</h1>
 }

If this section is not defined, an error will occur. We can use a required attribute to prevent page errors.

 @rendersection("testsection", required: false)

8. Why use html.partial?

This method is used to display a certain view specified by html string.

html.partial("testpartialview")

9. What is a partial view?

Partial view is equivalent to user controls in traditional web tables.
Its main purpose is to reuse these views, and they are usually placed in a shared folder

 html.partial()
 html.renderpartial()

10. Is MVC suitable for both Windows applications and Web applications?

Compared with Windows applications, the MVC architecture is more suitable for Web applications. For Windows applications, the MVP (Model View Presenter) architecture is better. If you use WPF and Silverlight, MVVM is more suitable.

11. How to keep Sessions in MVC?

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

12. I already have ASPX, why do I need Razor?

Compared to ASPX, Razor is a clean, lightweight and syntactically simpler. For example, ASPX to display time:

<%=DateTime.Now%>

In Razor, only one line is required: @DateTime.Now

13. How to implement Windows authentication in MVC?

You need to modify the web.config file and set the authentication mode to Windows.

 <authentication mode="Windows"/>
 <authorization>
 <deny users="?"/>
 </authorization>

Then in the controller or action, you can use the Authorize attribute to specify which user can access this controller or action. The code below sets it up so that only specified users can access it.

1 [Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
2 public class StartController : Controller
3 {
    
    
4 //
5 // GET: /Start/
6 [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
7 public ActionResult Index()
8 {
    
    
9 return View("MyView");
10 }
11 }

14. How to use form authentication in MVC?

Forms authentication is the same as ASP.NET forms authentication. The first step is to set the authentication mode to Forms. loginUrl points to the controller, not a page.

1 <authentication mode="Forms">
2 <forms loginUrl="~/Home/Login" timeout="2880"/>
3 </authentication>

We also need to create a controller to authenticate users. If the verification is passed, the cookies value needs to be set.

1 public ActionResult Login()
2 {
    
    
3 if ((Request.Form["txtUserName"] == "Shiv") &&
4 (Request.Form["txtPassword"] == "Shiv@123"))
5 {
    
    
6 FormsAuthentication.SetAuthCookie("Shiv",true);
7 return View("About");
8 }
9 else
10 {
    
    
11 return View("Index");
12 }
13 }

Other actions that need to be authenticated need to add an Authorize attribute. If the user does not have permission, it will be redirected to the login page.

1 [Authorize]
2 PublicActionResult Default()
3 {
    
    
4 return View();
5 }
6 [Authorize]
7 publicActionResult About()
8 {
    
    
9 return View();
10 }

15. How many different types of result types does MVC have?

Note: It is difficult to remember all 12 types. But some important ones you can remember, for example: ActionResult , ViewResult
, and JsonResult . The details are as follows:
There are 12 result types in MVC, the most important one is the ActionResult class, which is a basic class with 11 subtypes, as follows:

  • ViewResult - renders the specified view to the response stream
  • PartialViewResult - renders the specified partial view for the reactive stream
  • EmptyResult - returns an empty response result.
  • RedirectResult - Performs an HTTP redirect to the specified URL.
  • RedirectToRouteResult - Performs an HTTP redirect to a URL as determined by the routing engine based on routing data
  • JsonResult - Serializes a ViewData object into JSON format.
  • JavaScriptResult - returns a piece of Javascript code, which can be executed on the client.
  • ContentResult - writes content to the response stream, does not require view support.
  • FileContentResult - returns a file to the client.
  • FileStreamResult - returns a file to the client that provided the stream.
  • FilePathResult - returns a file to the client.

16. What is WebAPI?

HTTP is the most commonly used protocol. For many years in the past, the browser was our preferred client for exposing data using HTTP. But with each passing day, clients have evolved into many forms. We need to use HTTP to transfer data to different clients, such as: mobile phones, Javascript, Windows applications, etc.
WebAPI is a technology that exposes data through HTTP, and it follows REST rules.

17. What is packaging and compression in MVC?

Packaging and compression help us reduce the request time of a page, thereby improving page execution performance.
How to achieve high performance in packaging?
Our projects always require CSS and script files. Bundling helps you combine multiple Javascript and CSS files into a single file, thereby minimizing multiple requests into one.
For example, include the following web request to a page. This page requires two Javascript files, Javascript1.js and Javascript2.js.

18. Briefly describe the difference between Func and Action?

Func is a delegate with a return value, and Action is a delegate without a return value.

19. How to solve high concurrency problems in the project?

Answer: Use cache as much as possible, including user cache, information cache, etc., and spend more memory on cache, which can greatly reduce the interaction with the database and improve performance.
Optimize database query statements.
Optimize the database structure, do more indexes, and improve query efficiency.
Statistical functions should be cached as much as possible, or related reports can be counted on a daily basis or at regular intervals, avoiding statistical functions when needed, where
static pages can be used as much as possible, and container parsing should be reduced (generate dynamic content as much as possible) static html to display).
After solving the above problems, use server clusters to solve the bottleneck problem of a single server.

19. What other annotation attributes are used for validation in MVC?

If you want to check the length of characters, you can use StringLength

1 [StringLength(160)]
2 public string FirstName {
    
     get; set; }

If you want to use a registered expression, you can use RegularExpression.

1 [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email {
    
     get; set; }

If you want to check if a number is within a range, you can use Range .

1 [Range(10,25)]public int Age {
    
     get; set; }

Sometimes you want to compare the values ​​of two fields, we can use Compare.

1 public string Password {
    
     get; set; }
2 [Compare("Password")]
3 public string ConfirmPass {
    
     get; set; }

20. What is the difference between ActionResult and ViewResult?

ActionResult is an abstract class, and ViewResult is derived from ActionResult. ActionResult has several derived classes, such as: ViewResult, JsonResult, FileStreamResult, etc.
ActionResult can be used to develop polymorphic and dynamic animations. So if you dynamically run different types of views, ActionResult is the best choice. For example, in the following code, you can see that we have a DynamicView. Depending on the markup (IsHtmlView), it returns ViewResult or JsonResult.

21. How to perform packaging in MVC?

Open BundleConfig.cs in the App_Start folder.
In BundleConfig.cs, add the JS file path you want to package to the packaging collection. As follows:

1 bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
2 "~/Scripts/*.js"));

Below is the code of the BundleConfig.cs file:

1 public class BundleConfig
2 {
    
    
3 public static void RegisterBundles(BundleCollection bundles)
4 {
    
    
5 bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Includ
e(
6 "~/Scripts/*.js"));
7 BundleTable.EnableOptimizations = true;
8 }
9 }

Once you've merged the script into a file, you can call it with:

1 <%= Scripts.Render("~/Scripts/MyScripts") %>

22. What is the routing of MVC?

The routing selection function helps you define a URL rule and map URLs to controllers.

23. Where to write the route mapping table?

in the "global.asax" file.

24. What are the benefits of mentioning Area in MVC?

The benefits of Areas in MVC are as follows:
It allows us to organize Models, Views, and Controllers into separate functional parts of the application, such as administration, billing, customer support, and more.
It is easy to integrate with other zones created by another.
It is also easy to unit test.

25. Can you explain RenderBody and RenderPage in MVC?

RenderBody is like ContentPlaceHolder in web forms. This will live in layout pages and will render subpages/views. The layout page will have only one RenderBody() method. RenderPage also exists in the layout page, and multiple RenderPage() can exist in the layout page.

26. What are the filters of ASP.NET MVC?

Each request in APS.NET MVC (hereinafter referred to as "MVC") will be assigned to the corresponding controller and corresponding behavior method for processing, and before and after these processing, if you want to add some additional logical processing. This is where filters are used.
There are four types of filters supported by MVC, namely: Authorization (authorization), Action (behavior), Result (result) and Exception (exception).
Authorization: This type (or filter) is used to restrict access to a controller or a certain behavior method of a controller.
Exception: It is used to specify a behavior, and this specified behavior handles an exception thrown by a behavior method or a controller.
Action: Used to enter the processing before or after the action.
Result: used for processing before or after returning the result.

Guess you like

Origin blog.csdn.net/weixin_45091053/article/details/127177434