Click here to Skip to main content
15,893,487 members
Articles / Web Development / ASP.NET

Important Tips While Working on ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.39/5 (10 votes)
26 Oct 2017CPOL9 min read 11.3K   12   1
In this post, we will explore some important tips while working on MVC5. These tips are useful while hands on ASP.NET MVC.

Introduction

Here are some useful tips which we can look into while working on ASP.NET MVC project:

  • ViewEngine inside MVC is a to produce HTML (known as Razor)
  • HTML 5 has HTML tag with lang="en" to specify the default language
  • Meta tag with charset="utf-8" which specifies cross site scripting from some other sites do not harm our website.
  • Meta tag with name="viewport" is used for mobile devices. Without this meta tag, mobile assumes that your page needs 900px to display properly. With this meta tag, we are telling the device not to assume anything. Page fill fits the width of device automatically.
  • The script tag src="/Scripts/modernizr-2.5.3.js". This supports that HTML5 markup will work for every browser, even in IE-6.
  • Controller - Incoming HTTP Request goes to controller.
  • Model - Controller is responsible for calling Model. Model contains all the information that use needs to see.
  • View - Controller selects View to display model. It’s just a template.
  • MVC- It’s a design pattern to follow when you want to separate responsibilities of the components.
  • MVC is testable. Specially, Controller should be testable.
  • Naming convention plays a big role in MVC.
  • View has cshtml extension.
  • ViewBag is dynamically typed object inside MVC C#.
  • Models can reside in any Folder, even in a different Project.
  • Routing engine is the core part of ASP.NET. It’s not tide up to MVC. It can be used in webforms, WCF, webservices and MVC.
  • Routing engine MapRoute API provides a friendly name for URL, a pattern for route and parameters for route and default. Its job is to examine the URL and figure out where to send it for processing.
  • Controller Invokes Action. Looks for certain ActionName method.
  • Razor View is the cshtml extension. Consider them as a markup to display data inside the markup.
  • Heavy Calculation logic is not in the Views.
  • Views automatically handles HTML encoding.
  • Inside @{}, we can out C# code in a View.
  • Inside C# code in View, if we want some static or HTML text, we have to use @: before the text to be displayed.
  • RenderBody() method will render the .cshtml page to generate UI output.
  • _ViewStart.cshtml is the file which describes the common Layout for the application.
  • RenderSection() method is used to render sections defined anywhere within the View. It also deals in Ajax.
  • HTML helpers inside Views are helpful in creating action links, edit and validations and many others.
  • Anonymous objects are used heavily in MVC
  • TryUpdateModel() method goes through the process of Model Binding. Model Binder looks around for Update and updates the values.
  • How to build a custom logic in a Views? (need to drill this in depth)
  • Partial Views are used for re-usability across various views.
  • Html.Action() helper can be called in a _layout. It will call a sub-request to further call another Controller that builds its own Model independent of what the main controller is doing and render its own view, which is a partial view. It’s not a separate HTTP Request.
  • How Entity Framework populates Schema, it can be done by using EF-Migration. Migrations in EF is a tool which allows to configure schema with C# code and can keep the schema in sync with C# code for any changes. Example: in PM, type Enable-Migration -ContentTypeName "DBclassname"
  • AddOrUpdate() method in EF DbContext automatically checks in records exist then update it or insert it.
  • LinQ queries are strongly typed. That is the compiler and VS knows about the type of data we are querying against. LinQ uses Comprehension Query Syntax and Extension Method Syntax (Lambda Expression, useful for custom paging also).
  • Projection can be used to get columns to be listed inside Linq queries in C# code.
  • Example: Select aliasname;
  • The class which defines an extension method must be non-generic and static
  • Every extension method must be a static method.
  • Very often, our page needs more information than our Entity can have. In such situations, we use View-Model. Projection can be helpful here.
  • Using Comprehension expression or Extended expression doesn't affect in query performance anyway. It’s just another way to write the same query.
  • While developing, we should be very clear when to use method "get" and when to use "post". Usually get operation is a read operation and post operation is save, update, delete or process something on server.
  • While designing a search page, we can use get method as it's just reading the values and displaying to user. The get method wraps up the input in a query string to process request.
  • ASP.NET MVC matches things in Request by name.
  • Virtual keyword will create a wrapper at runtime.
  • Before CRUD operations, check ModelState IsValid.
  • If you don't want to update any specific field, use [Bind()] attribute with value Exclude="fieldname, can be comma separated"
  • Another way to do the same is to use a View-Model which will have properties defined inside it only.
  • The DataAnotations are used for Validations inside Model.
  • Custom Validation Attributes can be used for custom Validation on various pages.
  • Also implement IValidatableObject interface.
  • Inside Scripts folder, there is _refrences.js file which references the commonly used js files.
  • knockout.js is used in Model-View View-Model design pattern. It provides scripts like declarative data binding.
  • modernizer file is used to detect and run HTML 5 features on various browsers.
  • jquery.in.js is minified file having no comments or spaces so that browser can load the files faster.
  • jquery.unobtrusive-ajax.js acts like a bridge between jquery and ASP.NET MVC. It uses validations by supplying metadata to jquery validation.
  • Bundling can bundle number of files into a single file @ runtime. Inside Global.asax, in Application_Start, there is Bundle.config RegisterBundle.
  • @Scripts.Render("~/bundles/modenizr")
  • When we are running the application in release mode, there is only one file to be downloaded by the browser, while in debug mode, all files bundled are present for download each.
  • Ajax.BeginForm makes asynchronous request to the server; whereas BeginHtmlForm makes synchronous request to the server which means full postback on server.
  • Inside the controller, we can check if (Request.IsAjaxRequest()) {//do this}
  • There are three MVC features of unobtrusive JavaScript.
  • These are Ajax.BeginForm,
  • Ajax.ActionLink -> to make asynchronous request and update the screen instead of navigating browser to a new page.
  • Client Side Validation - > Unobtrusive JavaScript means we don't have JavaScript on click events, because that's obtrusive js to read the code and it also means to work if JavaScript on our browser in disabled, even then it will work because of its asynchronous postback.
  • using data- attributes, we can customize things like handling Ajax by using client side JavaScript instead and customizing messages, etc.
  • Jquery autocomplete UI documentation says, json should have a label property or value or both.
  • For Custom Paging, we use PagedList and PagedList.Mvc.
  • Authentication: Forms based (cookies, SSL required for security), OpenID/ OAuth (Third party like Microsoft or Twitter), Windows Authentication (Windows operating system auth with active directory and single sign on)
  • WebMatrix/WebSecurity is being used to borrow some features like Forms Authentication features from standard ASP.NET.
  • SimpleMemberShipProvider
  • Cross site Request Forgery -> [ValidateAntiForgeryToken]: Put it on all submit forms and also on cshtml files @Html.AntiForgeryToken()
  • ASP.NET MVC supports OpenID/OAuth via DotnetOpenAuth
  • OutputCache can be used to Cache data on Server, Client or Server-Client both (by using some proxy server in between).
  • VaryByHeader="X-Requested-With" is used for Ajax request. Also set Location=OutputCacheLocation.Server.
  • Caching can be best tested in production env. while testing.
  • Always use Cache Profile in config file instead of hard coding values.
  • While working on Resources files, make sure that the Access Modifier for resx file is set to Public, because Razor files are compiled separately as public and it can only access resx files if the files are public access.
  • VaryByHeader="X-Requested-With;Accept-Language" is used when dealing with resources files for multi-lingual support.
  • Use elmah for error handling.
  • Start developing Unit test cases sitting with Business Development/QA Team to develop possible test cases and Run All test cases.
  • Deployment & Testing are the most important part while developing a ASP.NET MVC application.
  • For CSS that are reused among the entire site, I define them in the section of the
    _Layout:<br />
    	@RenderSection("Styles", false)
    and if I need some view specific styles, I define the Styles section in each view: @section Styles {}
  • ASP.NET Web API is a framework for building web APIs on top of the .NET Framework.
  • A controller is an object that handles HTTP requests.
  • Controllers in Web API derive from the ApiController class instead of Controllerclass.
  • The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
  • The getJSON function sends the AJAX request. The response will be an array of JSON objects. The second parameter to getJSON is a callback function that is invoked when the request successfully completes.
  • Understanding Routing
  • For each HTTP message, the ASP.NET Web API framework decides which controller receives the request by consulting a route table.
  • When you create a new Web API project, the project contains a default route that looks like this: /api/{controller}/{id}
  • The {controller} and {id} portions are placeholders.
  • When the framework sees a URI that matches this pattern, it looks for a controller method to invoke, as follows: {controller} is matched to the controller name.
  • The HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.) {id}, if present, is matched to a method parameter named id.
  • Query parameters are matched to parameter names when possible
  • In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives a request, it routes the request to an action.
  • The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD operations as follows:
    • GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.
    • PUT updates a resource at a specified URI. PUT can also be used to create a new resource at a specified URI, if the server allows clients to specify new URIs. For this tutorial, the API will not support creation through PUT.
    • POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.
    • DELETE deletes a resource at a specified URI.

    Note: The PUT method replaces the entire product entity. That is, the client is expected to send a complete representation of the updated product. If you want to support partial updates, the PATCH method is preferred.

  • In Web API, parameters with complex types are DE serialized from the request body.

Point of Interest

There are many more important points which we will come across while working on ASP.NET MVC application. These tips can be useful while cracking an interview as well. So it's always good practice to have such tips handy on the internet so that we can reference them any time they are needed.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Working in .NET Technologies from the last +11 years and Exploring myself in .NET by learning, implementing and sharing my ideas of latest topics.
For further queries, shoot me a mail at sameersayani@gmail.com

Comments and Discussions

 
QuestionMy Vote Pin
Diwas Poudel6-Apr-18 17:36
Diwas Poudel6-Apr-18 17:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.