Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


You must login to ask a question.

You must login to add post.

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Latest Articles

Asp.Net MVC Cheatsheet Latest 2024 | Asp.Net Core – A Comprehensive Guide

Asp.Net MVC Cheatsheet Latest 2024 | Asp.Net Core – A Comprehensive Guide

Asp.Net MVC Cheatsheet: Our complete cheatsheet is your one-forestall aid to grasp ASP.NET MVC, masking a extensive variety of subjects, from controllers and views to routing and statistics handling. Whether you are seeking to decorate your self-practice or prepare for interviews, this cheatsheet has were given you protected.

Asp.Net MVC Cheatsheet

Application Folder | Asp.Net MVC Cheatsheet

App_Start: The “App_Start” directory is a central location within an ASP.NET MVC application where various configuration classes are organized to streamline and reduce clutter in the “Global.asax” file’s “Application_Start” method. It typically contains the following files:

  • AuthConfig.cs: This file is responsible for handling security settings, including the configuration of sites for OAuth login and authentication.
  • BundleConfig.cs: BundleConfig.cs is used for registering bundles, which enable bundling and minification of CSS and JavaScript files to optimize performance.
  • FilterConfig.cs: FilterConfig.cs is used to register global MVC filters. By default, it often registers filters like “HandleErrorAttribute,” which handles errors globally within the application.
  • RouteConfig.cs: RouteConfig.cs is used to configure MVC routing. It defines how incoming URLs are mapped to controller actions and plays a crucial role in determining the behavior of the application’s routes.
  • WebApiConfig.cs: WebApiConfig.cs is responsible for registering Web API routes and configuring settings for the Web API portion of the application. It ensures that Web API controllers and routes are properly configured.

Areas: “Areas” is a structural component in ASP.NET MVC that allows developers to partition a web application into smaller, self-contained sections. Each area typically includes its own controllers, views, models, and other necessary files. This separation helps maintain a clean and organized codebase, especially in large and complex applications.

Content: The “Content” directory is used to store static resources such as CSS files, images, and other assets that are essential for the appearance and functionality of the application. By convention, CSS files are often placed here and referenced from within the application’s views.

Controllers: The “Controllers” directory contains controller classes. Controllers handle user requests, process them, and determine which views to render or data to return as responses. They are a fundamental part of the MVC pattern, responsible for controlling the application’s behavior.

Images: The “Images” directory is used to store image files that are used within the application. These images can be referenced from various parts of the application, such as views and CSS files.

Models: The “Models” directory typically houses view models and domain model classes. View models are used to pass data from controllers to views, while domain models represent the application’s data and business logic.

Scripts: The “Scripts” directory is where JavaScript libraries and files are stored. These scripts are used to enhance the client-side functionality of the application and can be referenced in views or bundled and minified for optimized performance.

Views: The “Views” directory is responsible for managing the display and user interface (UI) of the application. It contains subdirectories for each controller, with corresponding views and partial views. Views define the presentation logic and are rendered to generate HTML pages for the user.

Html Helpers | Asp.Net MVC Cheatsheet

Here is a list of HTML form elements and corresponding methods in ASP.NET MVC’s Razor view engine that are used to render, modify, and output these elements:

  • Html.ActionLink: Outputs an anchor tag (<a>) to generate hyperlinks.
    Output: <a href=”…”>…</a>
  • Html.BeginForm: Outputs the opening <form> tag for creating HTML forms.
    Output: <form …>
  • Html.CheckBox: Renders an input element of type “checkbox.”
    Output: <input type=”checkbox” …/>
  • Html.DropDownList: Renders a dropdown list (<select>) with options.
    Output: <select …>…</select>
  • Html.EndForm: Outputs the closing </form> tag.
    Output: </form>
  • Html.Hidden: Renders a hidden input element.
    Output: <input type=”hidden” … />
  • Html.ListBox: Renders a listbox (<select>) with multiple selections allowed.
    Output: <select multiple …>…</select>
  • Html.Password: Renders an input element of type “password.”
    Output: <input type=”password” … />
  • Html.RadioButton: Renders an input element of type “radio.”
    Output: <input type=”radio” … />
  • Html.TextArea: Renders a textarea element for multiline text input.
    Output: <textarea …>…</textarea>
  • Html.TextBox: Renders an input element of type “text.”
    Output: <input type=”text” … />
  • Html.ValidationSummary: Returns an unordered list (<ul>) of validation messages that are present in the ModelStateDictionary object. It displays a summary of validation errors.
  • Html.ValidationMessage: Renders an error message for a particular field in the ModelState dictionary. It is used to display validation error messages associated with a specific form field.
  • Html.RouteLink: Generates a URL to a specific route. It allows you to create hyperlinks based on route definitions in your application.

These HTML helpers in ASP.NET MVC simplify the process of rendering HTML form elements and generating links while also facilitating model binding and validation.

@Html.AntiForgeryToken: Generates a hidden form field containing an anti-forgery token. This token is used to prevent cross-site request forgery (CSRF) attacks by validating it when the form is submitted.

@Html.AttributeEncode: Converts the specified attribute value to an HTML-encoded string. It helps protect against potential cross-site scripting (XSS) attacks by encoding attribute values.

@Html.Encode: Converts the specified value to an HTML-encoded string. It is used to prevent XSS attacks by encoding user-generated content before rendering it in the view.

@{ Html.EnableClientValidation(); }: Enables or disables client-side validation in the view. This is typically used in conjunction with unobtrusive JavaScript for client-side validation.

Html.EnableUnobtrusiveJavaScript: Enables or disables unobtrusive JavaScript in the view. Unobtrusive JavaScript promotes separation of concerns by moving JavaScript code out of HTML markup.

@Html.FormatValue: Used to format a value according to specified formatting rules. The exact behavior may depend on custom formatters or display templates configured in the application.

@Html.Raw: Returns markup that is not HTML-encoded. It allows you to render raw HTML content without encoding, so be cautious when using it to avoid XSS vulnerabilities.

@Html.Partial: Renders a partial view into a string. It allows you to include the content of a partial view within another view or layout.

@{Html.RenderPartial(..);}: Writes directly to the response output stream instead of returning a string. It renders the content of a partial view directly to the response.

@Html.Action: Executes a separate controller action and returns the result as a string. It allows you to invoke another action method and capture its rendered output within the current view.

Html.RenderAction: Executes a separate controller action and renders the result directly to the Response. This method is used when you want to render the output of another action within the current view as part of the response stream.

These HTML helper methods and Razor functions simplify common tasks in ASP.NET MVC views, such as encoding content, rendering partial views, enabling client-side validation, and managing anti-forgery tokens.

View Related & Others | Asp.Net MVC Cheatsheet

Asp.Net MVC Cheatsheet: Here are explanations for various Razor syntax elements used in ASP.NET MVC views:

  • @{ Layout = “…”; }: This directive is used to specify the layout page for the current view. It is equivalent to ASP.NET’s master page and defines the template that wraps the content of the view.
  • @model <StrongModelType>: This directive is used to define a strongly-typed model for the view. It specifies the type of the model that will be passed to the view, allowing for type-safe access to model properties.
  • @section <name> { }: This directive is used to define named sections within a view. These sections can be filled with content in the layout page or the view itself using @RenderSection.
  • @RenderBody: This is used in a layout page as a placeholder for the content of the views that use that layout. It renders the main content of the view.
  • @RenderPage: Renders the content of one Razor page within another page. It is typically used for including reusable code snippets or partial views.
  • @RenderSection: In layout pages, this directive renders the content of a named section that was defined in the view or layout.
  • IsSectionDefined: This is a method used to check whether a specific section is defined in the page. It returns a Boolean value indicating whether the section is defined.
  • DefineSection: This is used to create named content sections in content pages. These sections can be later filled in layout pages using @RenderSection.
  • @helper: The @helper directive is used to define a helper method within a Razor view. Helpers are reusable code snippets that can be called within the view to perform specific tasks or generate HTML content.
  • @functions: The @functions block is used to define server-side functions that can be reused within the view. These functions are typically pure server-side methods.
  • @ViewBag.<myData>: This syntax is used to access data passed between a Controller and a View via the ViewBag. The ViewBag is a dynamic property that allows data to be stored and retrieved in a loosely-typed manner.
  • @ViewData[“myData”]: This syntax is used to access data passed between a Controller and a View via the ViewData dictionary. ViewData is a dictionary-like container for passing data between a Controller and a View.
  • @tempdata: TempData is used to pass state between action methods. It is typically used for storing data temporarily between redirects or during a single HTTP request. TempData is part of the ASP.NET session state.

Action Method Result | Cheat Sheet for ASP.NET MVC

Asp.Net MVC Cheatsheet: Here is a summary of various ActionResult types in ASP.NET MVC:

ActionResult: A generic return type for an action method that is used to perform a framework-level operation on behalf of the action method.

ContentResult: Used to return a user-defined content type that is the result of an action method. It allows you to return raw content as a response, such as plain text or HTML.

EmptyResult: Used when you want to return nothing from a Controller action. It represents an empty response.

FileContentResult: Sends the contents of a binary file to the response. It is used to return binary files, such as images or documents, as the response.

FilePathResult: Sends the contents of a file to the response. It allows you to return a file located on the server as the response.

FileResult: Used to return the content of a file to the browser. It is typically used for serving files like images, PDFs, or other downloadable content.

FileStreamResult: Sends binary content to the response by using a Stream instance. This is useful for streaming large files or dynamic content.

HttpNotFoundResult: Returns a 404 status code to indicate that the requested resource was not found. It is used to handle cases where a resource is missing.

HttpStatusCodeResult: Used to return a specific HTTP response status code and an optional description. This allows you to customize the HTTP status code of the response.

HttpUnauthorizedResult: Returns a 401 status code to indicate an unauthorized HTTP request. It is often used for authentication and authorization purposes.

JsonResult: Used to return a serialized JSON object as the response. It is commonly used in AJAX requests to send data back to the client in JSON format.

JavaScriptResult: Returns a JavaScript script that can be executed on the client-side. It is used for dynamic client-side scripting.

PartialViewResult: Renders a partial view, which is a portion of a view, often used for rendering user controls or reusable components.

RedirectResult: Redirects to a specified URI or URL. It instructs the browser to navigate to the specified location.

RedirectToRouteResult: Redirects to a route defined in the routing configuration. It provides a way to perform redirection based on route definitions.

ValueProviderResult: Represents the result of binding a value, such as from a form post or query string, to an action-method argument property or to the argument itself. It is used for model binding and data retrieval.

ViewEngineResult: Represents the result of locating a view engine. It is used internally by ASP.NET MVC to find and render views.

ViewResult: Renders a view as a web page. It is used to generate HTML content that represents the user interface of a web page.

Attributes | Asp.Net MVC Cheatsheet

Asp.Net MVC Cheatsheet: Here is an explanation of the mentioned filter-related attributes in ASP.NET MVC:

ActionFilterAttribute: This attribute represents the base class for filter attributes in ASP.NET MVC. Filters are components that can be used to perform various tasks before or after an action method is executed. They can be applied at the action or controller level. ActionFilterAttribute provides hooks to execute code before and after action method execution, such as OnActionExecuting and OnActionExecuted methods, allowing developers to implement custom behavior for specific actions or controllers.

ActionMethodSelectorAttribute: This attribute is used to influence the selection of an action method within a controller. It can be applied to multiple action methods within a controller to define criteria for method selection. 

For example, you can create custom action method selectors that consider various factors, such as HTTP request parameters or headers, to determine which action method should be executed for a particular request.

ActionNameSelectorAttribute: This attribute affects the selection of an action method based on the name of the action. It allows you to specify criteria for selecting an action method with a particular name when multiple actions in a controller have similar names.

CustomModelBinderAttribute: This attribute is used to invoke a custom model binder for a specific action parameter or property. Model binders are responsible for mapping data from HTTP requests to action method parameters. By applying CustomModelBinderAttribute to a parameter or property, you can specify a custom model binder that will be used to bind data to that parameter or property, allowing you to implement custom data binding logic.

FilterAttribute: This is the base class for both action and result filter attributes in ASP.NET MVC. Action filters are executed before and after the execution of an action method, while result filters are executed before and after the execution of a result (e.g., a ViewResult). Filters are a powerful feature in ASP.NET MVC that allow you to add cross-cutting concerns, such as logging, authentication, or caching, to your application by applying attributes to controllers or action methods.

Here’s an explanation of various attributes used in ASP.NET MVC for controlling and customizing the behavior of action methods:

[AcceptVerbs(…)]: Used to specify the HTTP verbs that an action method will respond to. It restricts the types of HTTP requests that can be handled by the method.

[ActionName(…)]: Used to define a custom name for an action method. This allows you to use a different name for the action method in the URL while keeping a different name in the code.

[AdditionalMetadata(…)]: Used to populate the ModelMetadata.AdditionalValues dictionary for a model property. You can attach additional metadata to model properties, which can be useful for customizing data annotations or providing extra information about the property.

[AllowHtml]: Allows HTML markup during model binding by skipping request validation for the property. This attribute is used when you want to accept and store HTML content as part of your model data.

[AsyncTimeout(…)]: Sets the timeout value, in milliseconds, for an asynchronous method. It defines the maximum allowed execution time for an asynchronous action method.

[Authorize(…)]: Restricts access by callers to an action method. It is used to specify authorization rules and control who can access a particular action method.

[ChildActionOnly]: Indicates that an action method should be called only as a child action. It prevents direct access to the action method via a URL and is typically used for rendering partial views.

[HandleError(…)]: Used to handle an exception that is thrown by an action method. It specifies a view to display when an unhandled exception occurs.

[HiddenInput(…)]: Used to render a property or field value as a hidden input element. This attribute is applied to model properties or fields to hide them in forms.

[HttpDelete]: Restricts an action method to handle only HTTP DELETE requests. It specifies that the method should respond only to HTTP DELETE requests.

[HttpGet]: Restricts an action method to handle only HTTP GET requests. It specifies that the method should respond only to HTTP GET requests.

[HttpPost]: Restricts an action method to handle only HTTP POST requests. It specifies that the method should respond only to HTTP POST requests.

[HttpPut]: Restricts an action method to handle only HTTP PUT requests. It specifies that the method should respond only to HTTP PUT requests.

[ModelBinder(..)]: Used to associate a model type with a custom model binder. It allows you to define how a particular model type should be bound from incoming HTTP request data.

[NoAsyncTimeout]: Sets the timeout value to infinite (never) for asynchronous methods. It means that there is no specific timeout for the asynchronous action method.

[NonAction]: Indicates that a controller method is not an action method. It prevents a method from being treated as an action and callable via a URL.

[OutputCache(..)]: Marks an action method whose output will be cached. It allows you to cache the output of an action to improve performance.

[Remote(…)]: Used to invoke server-based validation from the client side. It specifies a remote server method to call for validation in response to a client-side request.

[RequireHttps]: Forces an unsecured HTTP request to be re-sent over HTTPS. It ensures that the action method is accessible only via a secure HTTPS connection.

[SessionState(…)]: Specifies the session state behavior of the controller. It controls how the controller interacts with session data.

[ValidateInput(…)]: Marks action methods whose input must be validated. It is used to enable or disable request validation for specific action methods to prevent cross-site scripting (XSS) attacks.

Data Annotations for Model | Asp.Net MVC Cheatsheet

Asp.Net MVC Cheatsheet: Here are explanations of various data annotation attributes used in ASP.NET MVC for model validation and metadata customization:

[Bind(…)]: Lists fields to exclude or include when binding parameters or form values to model properties. It allows you to control which fields are included or excluded during model binding.

[Compare(“…”)]: Compares the value of a property with another property. It is used for ensuring that two properties have matching values, such as when confirming a password.

[CreditCard]: Specifies that a data field value is a credit card number. It can be used for both validation and formatting.

[DataType(DataType.<type>)]: Used for formatting purposes, not for validation. It informs the framework about the intended data type of a property, which can be used for rendering purposes.

[DisplayName(…)]: Defines the text to be used on form fields and validation messages. It customizes the display name of a property for better user interface presentation.

[EmailAddress]: Validates that a property contains a valid email address format. It checks whether the input is in a valid email address format.

[FileExtensions(Extensions = “jpg,png…”)]: Validates file name extensions for file uploads. It ensures that uploaded files have the specified file extensions.

[Key]: Denotes one or more properties that uniquely identify an entity. It is often used in data models to specify primary key properties.

[MaxLength(…)]: Defines the maximum length of array or string data allowed in a property. It specifies a maximum character limit for a string property.

[MinLength(…)]: Defines the minimum length of array or string data allowed in a property. It specifies a minimum character limit for a string property.

[Phone]: Specifies phone number validation using a regular expression. It ensures that the input matches the specified regular expression pattern for phone numbers.

[Range(…)]: Provides a maximum and minimum value for a numeric field. It validates that a property’s value falls within the specified range.

[RegularExpression(…)]: Specifies that a data field value must match the specified regular expression pattern. It allows you to define custom validation patterns.

[Required(…)]: Indicates that the property is a required field. It ensures that a value is provided for the property during model binding.

[StringLength(…)]: Defines a maximum length for a string field. It sets an upper limit on the number of characters allowed for a string property.

[ScaffoldColumn(…)]: Allows hiding fields from editor forms. It is used to exclude specific properties from being generated in editor forms or views.

[Url]: Provides URL validation. It ensures that a property contains a valid URL format.

These data annotation attributes help define data validation rules, customize metadata, and enhance the behavior of model properties in ASP.NET MVC applications.

Read Also: Career in Cyber Security

If you are looking for some useful links on the topic of ASP.NET MVC and Core, you might find these resources helpful:

  • ASP.NET Core MVC Tutorial: This is a comprehensive tutorial that covers the basics of ASP.NET Core MVC framework, such as models, views, controllers, routing, data access, validation, security, and more. It also includes practical examples and exercises to help you learn and practice the concepts.
  • Routing in ASP.NET Core: This is an article that explains the low-level details of ASP.NET Core routing, such as how routes are matched, how to configure route templates, how to use route data and query strings, how to create custom route constraints and route handlers, and more. It also shows how to use the built-in routing features for controllers and Razor Pages.

Related Posts

Leave a comment

You must login to add a new comment.