Unit 3: Backend Development Using Asp.Net - Subjective Questions
INT402 — Modern Web Programming Tools And Techniques • Practice Questions with Detailed Answers
20 questions
Describe the standard folder and file structure of an ASP.NET Core MVC project. Explain the purpose of its important folders and configuration files.
An ASP.NET Core MVC project follows a convention-based folder structure.
- Controllers: Contains controller classes that receive HTTP requests, interact with models, and select views. Controller names usually end with
Controller, such asHomeController. - Models: Contains domain models, view models, validation models, and data-related classes.
- Views: Contains Razor view files with the
.cshtmlextension. Views are normally organized into controller-specific subfolders. - Views/Shared: Stores common views such as layouts, partial views, and error pages.
- wwwroot: Contains publicly accessible static files, including CSS, JavaScript, images, and client-side libraries.
- Properties: Usually contains
launchSettings.json, which defines development-time launch profiles and environment variables. - Program.cs: Acts as the application entry point. It registers services, builds the application, and configures the HTTP request pipeline.
- appsettings.json: Stores configuration settings such as connection strings, logging options, and application-specific values.
- Dependencies: Represents NuGet packages, framework references, and other project dependencies.
- Project file: The
.csprojfile defines the target framework, package references, and build settings.
This organization supports the separation of concerns and makes an MVC application easier to develop, test, and maintain.
Explain the steps involved in building and configuring a basic web application using ASP.NET Core MVC.
The main steps for creating an ASP.NET Core MVC application are:
- Create the project: Use Visual Studio or execute
dotnet new mvc -n MyApplicationfrom the command line. - Register MVC services: Add MVC services to the dependency-injection container in
Program.cs:
builder.Services.AddControllersWithViews();- Build the application:
var app = builder.Build();- Configure middleware: Add middleware for exception handling, HTTPS redirection, static files, routing, authorization, and endpoint execution.
- Define conventional routing:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");- Create a controller: Add a controller such as
HomeControllerwith an action method that returns a view. - Create a view: Add
Index.cshtmlunderViews/Home. - Add models if required: Models represent application data and business rules.
- Run the application: Use
dotnet runor the Run command in Visual Studio. - Test the application: Open the configured URL and verify routing, views, static files, and form operations.
The sequence of middleware in Program.cs is important because each middleware component processes the request in the order in which it is registered.
Define the MVC architectural pattern. Explain the responsibilities of the Model, View, and Controller components.
MVC stands for Model-View-Controller. It separates a web application into three cooperating components.
-
Model:
- Represents application data and business rules.
- Performs validation and may communicate with a database or service.
- Examples include
Product,Student, andOrderclasses.
-
View:
- Represents the user interface.
- Displays data received from a controller.
- In ASP.NET Core MVC, views are commonly written as Razor
.cshtmlfiles. - A view should contain minimal business logic.
-
Controller:
- Receives and handles HTTP requests.
- Calls model or service-layer operations.
- Selects a view or returns another action result.
- Passes the required data to the selected view.
Typical flow:
- The browser sends a request.
- Routing selects a controller action.
- The controller obtains or modifies model data.
- The controller passes data to a view.
- The view renders an HTML response.
MVC improves separation of concerns, maintainability, testability, and parallel development.
Describe Model-View-Controller communication in ASP.NET Core MVC by tracing the complete lifecycle of a request and response.
The MVC request-response lifecycle can be described as follows:
- Request creation: A browser sends an HTTP request to the server.
- Middleware pipeline: The request passes through configured middleware components such as exception handling, static-file handling, authentication, authorization, and routing.
- Route matching: Endpoint routing analyzes the URL and identifies the appropriate controller and action.
- Controller creation: ASP.NET Core creates the controller, usually through dependency injection.
- Model binding: Values from route data, query strings, forms, and request bodies are mapped to action parameters or model properties.
- Model validation: Validation attributes are evaluated, and errors are recorded in
ModelState. - Action execution: The controller action executes business logic, calls services, and obtains model data.
- Data transfer: The controller supplies data through a strongly typed model,
ViewData,ViewBag, or another suitable mechanism. - View selection: The controller returns a
ViewResult, identifying the Razor view to render. - View rendering: The Razor engine combines the view, model, layout, sections, and partial views to generate HTML.
- Response: The generated HTML is returned through the middleware pipeline to the browser.
The controller acts as the coordinator. The model does not directly render the interface, and the view should not directly handle request-processing or database logic.
Explain how requests are handled in ASP.NET Core MVC. Discuss the roles of middleware, routing, controllers, actions, and action results.
ASP.NET Core handles requests through an ordered HTTP request pipeline.
- Middleware: Each middleware component can inspect the request, perform an operation, call the next component, and inspect the response. Examples include exception handling, HTTPS redirection, static files, authentication, and authorization.
- Routing: Routing matches an incoming URL to an endpoint. Conventional routing may use the pattern
{controller=Home}/{action=Index}/{id?}, while attribute routing uses attributes such as[Route("products/{id}")]. - Controller: A controller groups related request-handling operations. It usually inherits from
Controller. - Action method: A public controller method processes a specific request. Attributes such as
[HttpGet]and[HttpPost]restrict the supported HTTP method. - Model binding and validation: Request values are converted into action parameters, followed by validation.
- Action result: An action can return different results, including:
ViewResultfor an HTML viewRedirectToActionResultfor redirectionJsonResultfor JSON dataContentResultfor plain textNotFoundResultfor HTTP status404FileResultfor a downloadable file
After the action result is executed, ASP.NET Core creates the HTTP response and sends it back through the middleware pipeline.
What is the Razor View Engine? Explain important Razor syntax rules with suitable examples.
The Razor View Engine combines HTML markup with server-side C# code to generate dynamic web content. Razor files normally use the .cshtml extension.
Important syntax rules include:
- Razor transition character: The
@symbol changes from HTML to C#.
cshtml
<h1>Welcome, @Model.Name</h1>
- Code block: Multiple C# statements are enclosed in
@{ }.
cshtml
@{
var title = "Product List";
var count = Model.Count;
}
- Explicit expression: Parentheses remove ambiguity.
cshtml
<p>@(Model.Price * Model.Quantity)</p>
- Conditional statement:
cshtml
@if (Model.IsAvailable)
{
<span>In Stock</span>
}
else
{
<span>Out of Stock</span>
}
- Loop:
cshtml
@foreach (var item in Model)
{
p>@item.Name</p
}
- Strongly typed model: The
@modeldirective declares the model type.
cshtml
@model Product
- Comments: Razor comments use
@* comment *@and are not sent to the browser. - Escaping
@: Use@@when a literal@symbol is required.
Razor usually applies HTML encoding to displayed values, helping reduce cross-site scripting risks.
Explain the purpose and use of Layout pages, Sections, and the _ViewStart.cshtml file in ASP.NET Core MVC.
ASP.NET Core MVC provides layouts, sections, and view-start files to create consistent and reusable interfaces.
Layout
A layout is a common page template containing shared HTML such as the header, navigation bar, footer, CSS references, and scripts. It is commonly stored as Views/Shared/_Layout.cshtml.
@RenderBody()displays the main content of the current view.@RenderSection("Scripts", required: false)displays an optional named section.
Sections
A view defines content for a layout section using:
cshtml
@section Scripts {
<script src="~/js/page.js"></script>
}
Sections are useful when individual pages require page-specific scripts or styles. A section can be required or optional, but it can only be rendered by the immediate layout.
_ViewStart.cshtml
The _ViewStart.cshtml file contains code that should run before each full view in its folder hierarchy. It commonly selects the layout:
cshtml
@{
Layout = "_Layout";
}
Using _ViewStart.cshtml avoids assigning the same layout separately in every view. Together, these features reduce duplication and provide a consistent site design.
Compare the major techniques available for passing data from a controller to a view in ASP.NET Core MVC.
A controller can pass data to a view using several techniques.
| Technique | Type safety | Lifetime | Typical use |
|---|---|---|---|
| Strongly typed model | Yes | Current request | Main structured page data |
| View model | Yes | Current request | Data combined specifically for one view |
ViewData |
No; values are object |
Current request | Small supplementary values |
ViewBag |
No; dynamic access | Current request | Small supplementary values |
TempData |
No | Current and usually next request | Messages after redirection |
Strongly typed model
The controller passes an object through View(model), and the view declares its type with @model. This provides IntelliSense, compile-time checking, and clear structure.
View model
A view model combines exactly the fields required by a page. It prevents the view from depending directly on complex domain entities.
ViewData
ViewData is a dictionary accessed using string keys, for example ViewData["Title"]. Casting may be required.
ViewBag
ViewBag is a dynamic wrapper around ViewData, for example ViewBag.Title.
TempData
TempData retains data until it is read, normally across one redirect. It is useful for success or error notifications.
For important structured data, a strongly typed view model is generally the preferred technique.
Distinguish between ViewBag and ViewData in ASP.NET Core MVC. Mention their similarities, differences, and limitations.
ViewBag and ViewData are used to transfer small amounts of data from a controller to a view during the same request.
Similarities
- Both have a current-request lifetime.
- Both are suitable for supplementary data such as page titles or short messages.
- Both lack compile-time type safety.
ViewBaginternally uses the same underlying storage asViewData.
Differences
ViewData |
ViewBag |
|---|---|
A ViewDataDictionary |
A dynamic wrapper around ViewData |
| Uses string keys | Uses property-style syntax |
Example: ViewData["Title"] |
Example: ViewBag.Title |
| Casting may be needed | Dynamic conversion occurs at runtime |
Misspelled keys can return null |
Misspelled properties can cause runtime problems |
Because both refer to the same underlying collection, setting ViewData["Message"] allows the value to be accessed through ViewBag.Message.
Limitations
- Data is lost after a redirect.
- Errors are usually discovered at runtime.
- They are unsuitable for large or complex page models.
A strongly typed model or view model is preferable for essential page data.
Explain TempData in ASP.NET Core MVC. Describe its lifetime and the purpose of the Peek and Keep methods.
TempData stores data temporarily and makes it available to the current request and usually the next request. It is especially useful when an action redirects to another action.
Example:
TempData["Success"] = "Record saved successfully.";
return RedirectToAction("Index");The redirected view can read the value:
cshtml
@if (TempData["Success"] != null)
{
p>@TempData["Success"]</p
}
Lifetime behavior
- A value normally remains until it is read.
- After a normal read, it is marked for deletion at the end of the request.
- ASP.NET Core commonly stores TempData through a cookie-based provider, although a session-based provider can also be configured.
Peek
TempData.Peek("key") reads a value without marking it for deletion.
Keep
TempData.Keep("key") preserves a value after it has been read. Calling Keep() without a key preserves all values.
TempData should contain small, short-lived values such as status messages. Large or sensitive objects should not be placed in cookie-based TempData.
What is session state in ASP.NET Core? Explain how sessions are configured, accessed, and managed.
Session state stores user-specific data across multiple requests. A session identifier is generally stored in a browser cookie, while the actual session values are stored on the server or in a distributed cache.
Configuration
- Register a cache and session services:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});- Add session middleware before endpoint execution:
app.UseSession();Accessing session values
HttpContext.Session.SetString("UserName", "Asha");
string? name = HttpContext.Session.GetString("UserName");
HttpContext.Session.SetInt32("CartCount", 3);
int? count = HttpContext.Session.GetInt32("CartCount");Management considerations
- A session expires after the configured idle timeout.
Remove("key")deletes one value, whileClear()removes all values.- Session data is not strongly typed by default.
- In multi-server applications, a distributed provider such as Redis or SQL Server should be used.
- Sensitive data should not be stored unnecessarily in a session.
Session state is suitable for temporary user-specific information such as shopping-cart identifiers, but persistent business data belongs in a database.
Compare cookies, sessions, TempData, hidden fields, and query strings as state-management techniques in ASP.NET Core applications.
HTTP is stateless, so applications use state-management techniques to preserve data between requests.
| Technique | Storage location | Lifetime | Visibility | Suitable use |
|---|---|---|---|---|
| Cookies | Browser | Until expiry or deletion | Stored on client | Preferences and identifiers |
| Session | Server or distributed cache | Until timeout | Only session ID is normally in browser | User-specific temporary state |
| TempData | Cookie or session provider | Usually until read in next request | Provider-dependent | Messages after redirects |
| Hidden fields | HTML form | Until form submission | Visible in page source | Returning page-specific values |
| Query string | URL | Present in current/bookmarked URL | Fully visible | Search, filtering, paging |
Important observations
- Cookies have limited size and can be modified by users unless protected.
- Sessions can consume server resources and require distributed storage in a web farm.
- TempData is intended for short-lived values, not general persistence.
- Hidden fields can be modified by users and must never be trusted without validation.
- Query strings are bookmarkable but should not contain secrets.
The correct technique depends on the required lifetime, size, sensitivity, scalability, and whether the state should be visible to the user.
Explain how QueryString values are used in ASP.NET Core MVC. State their benefits, limitations, and security considerations.
A query string is the portion of a URL following ?. Multiple values are separated by &.
Example:
/products/search?category=books&page=2ASP.NET Core model binding can map these values directly to action parameters:
public IActionResult Search(string category, int page = 1)
{
return View();
}Values can also be read from the request:
string category = Request.Query["category"].ToString();Benefits
- Easy to construct and test.
- Suitable for search, filtering, sorting, and pagination.
- URLs can be bookmarked and shared.
- Does not require server-side state.
Limitations
- Values are visible in the address bar.
- URL length is limited by browsers and servers.
- Query strings are unsuitable for large or complex data.
- Users can freely modify their values.
Security considerations
- Never place passwords, tokens, or confidential information in a query string.
- Validate and authorize all supplied values.
- Do not assume that a hidden or encoded value is trustworthy.
- Use parameterized database operations to prevent injection attacks.
Query-string values should be treated as untrusted user input.
Describe how forms are created and processed in ASP.NET Core MVC using Form Tag Helpers and Input Tag Helpers.
ASP.NET Core MVC forms can be created using HTML combined with Tag Helpers.
A strongly typed Razor form may be written as:
cshtml
@model StudentViewModel
<form asp-controller="Student" asp-action="Create" method="post">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<button type="submit">Save</button>
</form>
Important Tag Helpers
- Form Tag Helper:
asp-controllerandasp-actiongenerate the form action URL. - Input Tag Helper:
asp-forgenerates attributes such asname,id,type, and validation metadata based on a model property. - Label Tag Helper:
asp-forcreates a label associated with the input. - Validation Message Tag Helper:
asp-validation-fordisplays a property-specific validation error. - Validation Summary Tag Helper:
asp-validation-summarydisplays multiple validation errors. - Select Tag Helper:
asp-itemsgenerates options for a selection list.
The form submits key-value pairs to an action marked with [HttpPost]. Model binding creates the action parameter, and validation errors are stored in ModelState. POST forms also commonly include an antiforgery token, which should be verified to protect against cross-site request forgery.
Define model binding in ASP.NET Core MVC. Explain its data sources, operation, and use with simple and complex types.
Model binding automatically converts incoming HTTP request data into action parameters or properties of complex model objects.
Common data sources
- Form fields
- Route values
- Query-string values
- Request-body data when an appropriate formatter and attribute are used
- Uploaded files
Simple-type binding
public IActionResult Details(int id)The framework attempts to obtain id from available request-value sources and convert it to an integer.
Complex-type binding
[HttpPost]
public IActionResult Create(StudentViewModel model)If the submitted field names match properties such as Name and Email, ASP.NET Core creates a StudentViewModel and assigns the converted values.
Binding attributes
[FromQuery]binds from the query string.[FromRoute]binds from route data.[FromForm]binds from submitted form data.[FromBody]binds from the request body.[BindProperty]supports binding to controller or Razor Page properties.
Conversion and validation problems are added to ModelState. Developers should use dedicated input models and allow-list intended properties to reduce over-posting risks.
Explain server-side form validation in ASP.NET Core MVC using data-annotation attributes and ModelState.
Server-side validation checks submitted data on the server and must be performed even when client-side validation is enabled.
A model can define validation rules using data annotations:
public class RegisterViewModel
{
[Required]
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Range(18, 100)]
public int Age { get; set; }
}The POST action checks ModelState:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Success");
}How it works
- Model binding populates model properties.
- Validation attributes are evaluated.
- Conversion and validation errors are stored in
ModelState. - If the model is invalid, the same view is returned so that errors and submitted values can be displayed.
- Custom errors can be added with
ModelState.AddModelError.
Server-side validation is authoritative because client-side checks can be disabled or bypassed.
Describe client-side validation in ASP.NET Core MVC. How is it connected with model validation attributes and unobtrusive validation?
Client-side validation checks form values in the browser before the form is submitted. It improves usability by displaying immediate feedback and reducing unnecessary requests.
Working mechanism
- Validation attributes such as
[Required],[Range], and[StringLength]are placed on model properties. - Tag Helpers generate HTML
data-val-*attributes from those rules. - jQuery Validation and jQuery Unobtrusive Validation read the generated attributes.
- Errors are displayed through
asp-validation-forandasp-validation-summaryelements.
A view commonly loads validation scripts through:
cshtml
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Advantages
- Provides immediate feedback.
- Reduces avoidable server requests.
- Improves the user experience.
- Reuses many rules declared on the server model.
Limitation
Client-side validation is not a security boundary. A user can disable JavaScript, modify HTML, or send requests directly. Therefore, the same data must always be validated on the server.
Compare server-side and client-side form validation. Why are both required in a well-designed ASP.NET Core application?
Server-side and client-side validation serve complementary purposes.
| Client-side validation | Server-side validation |
|---|---|
| Runs in the browser | Runs on the web server |
| Gives immediate feedback | Runs after a request reaches the server |
| Reduces unnecessary submissions | Provides authoritative validation |
| Can be disabled or bypassed | Cannot be bypassed when correctly implemented |
| Useful for formatting and basic field rules | Can apply business rules and database checks |
| Depends on browser-side scripts | Works independently of JavaScript |
Why both are required
- Client-side validation improves responsiveness and user experience.
- Server-side validation protects application integrity and security.
- A malicious user can construct a request without using the application's form.
- Certain rules, such as checking whether an email already exists, require server-side data access.
- Shared data annotations can support both types of validation, reducing duplicated rules.
A correct application treats client-side validation as a convenience and server-side validation as mandatory. Data should be saved only when ModelState.IsValid is true and all necessary business rules have passed.
Explain the Post-Redirect-Get pattern. Demonstrate how TempData can be used with it to process a successful form submission.
Post-Redirect-Get, abbreviated as PRG, is a pattern used to prevent duplicate form submissions.
Sequence
- A user requests a form with
GET. - The user submits the form with
POST. - The server validates and processes the submitted data.
- After success, the POST action returns a redirect.
- The browser follows the redirect by sending a new
GETrequest.
Example:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ProductViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Save the product.
TempData["Success"] = "Product created successfully.";
return RedirectToAction("Index");
}The redirected page can display the message:
cshtml
@if (TempData["Success"] is string message)
{
<div class="alert alert-success">@message</div>
}
Benefits
- Refreshing the final page repeats only the
GET, not the originalPOST. - It reduces accidental duplicate insertions.
- It creates a clean, bookmarkable final URL.
- TempData carries a short-lived confirmation message across the redirect.
When validation fails, the action should normally return the same view directly rather than redirecting, so that ModelState errors remain available.
Design the request flow for an ASP.NET Core MVC student-registration form. Include the model, GET and POST actions, Razor form, model binding, validation, and redirection.
A student-registration feature can be designed as follows.
1. View model
public class StudentViewModel
{
[Required]
[StringLength(60)]
public string Name { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Range(16, 100)]
public int Age { get; set; }
}2. GET action
[HttpGet]
public IActionResult Create()
{
return View(new StudentViewModel());
}3. Razor form
cshtml
@model StudentViewModel
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<label asp-for="Email"></label>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
<label asp-for="Age"></label>
<input asp-for="Age" />
<span asp-validation-for="Age"></span>
<button type="submit">Register</button>
</form>
4. POST action
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(StudentViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Map the view model and save the student.
TempData["Success"] = "Student registered successfully.";
return RedirectToAction("Index");
}Request flow
- The GET action displays the form.
- Tag Helpers generate correctly named fields and validation metadata.
- On submission, model binding maps form fields to
StudentViewModel. - Data annotations populate
ModelStatewith validation errors. - Invalid data returns the same view with messages.
- Valid data is saved, a TempData message is created, and PRG redirects to
Index.
This design provides type safety, validation, antiforgery protection, and protection against duplicate submissions.
Describe the standard folder and file structure of an ASP.NET Core MVC project. Explain the purpose of its important folders and configuration files.
An ASP.NET Core MVC project follows a convention-based folder structure.
- Controllers: Contains controller classes that receive HTTP requests, interact with models, and select views. Controller names usually end with
Controller, such asHomeController. - Models: Contains domain models, view models, validation models, and data-related classes.
- Views: Contains Razor view files with the
.cshtmlextension. Views are normally organized into controller-specific subfolders. - Views/Shared: Stores common views such as layouts, partial views, and error pages.
- wwwroot: Contains publicly accessible static files, including CSS, JavaScript, images, and client-side libraries.
- Properties: Usually contains
launchSettings.json, which defines development-time launch profiles and environment variables. - Program.cs: Acts as the application entry point. It registers services, builds the application, and configures the HTTP request pipeline.
- appsettings.json: Stores configuration settings such as connection strings, logging options, and application-specific values.
- Dependencies: Represents NuGet packages, framework references, and other project dependencies.
- Project file: The
.csprojfile defines the target framework, package references, and build settings.
This organization supports the separation of concerns and makes an MVC application easier to develop, test, and maintain.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →