Learn C#.NET, ASP.NET MVC 5,ASP.NET Core that you can increase your knowledge and coding to develop the real-time project.

Monday, May 6, 2019

Action Method In ASP.NET MVC 5


We will learn Action Method in ASP.NET MVC 5 with example and example of Action Method in ASP.NET MVC 5 with example in this article. The default configuration of the action method in asp.net MVC 5.

Action Method in ASP.NET MVC 5


Following are the previews article on ASP.NET MVC


Action Method in ASP.NET MVC-5:


ASP.NET MVC action methods are responsible to execute the request and generate a response on it. All the public method of MVC controller are action method. If we want the public method is non-action method then we can decorate the action method by “NonAction” attribute. It will restrict the action method to render on the browser.

To work with action method need to remember the following points. 

  • The action method is a public non-static method.
  • Action method cannot be a private or protected method.
  • Action method cannot contain ref and out parameters.
  • Action method cannot be an extension method.
  • Action method cannot be overloaded.

  

Example of an action method in ASP.NET MVC as follows.

Action Method in ASP.NET MVC 5


public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
}

You can see in the above action method example, the Index() method is a public method which is inside the HomeController class. And the return type of the action method is ActionResult it can return using View()method. So every public method inside the Controller is an action method in MVC. 

Action method can not be private or protected method: 

public class HomeController : Controller
    {
        // GET: Home
        private ActionResult Index()
        {
            return "This is Index Method";        }
}


If you provide the private or protected access modifier in then it will provide the error to the user I.e. “resource can not found” as follows.
Action Method In  MVC 5

Action method can not contain ref and out parameters. 

    public string Index(ref int id)
        {
            return "This is Index Method" +id;
        }

       public string Index(out int id)
        {
          id =0;
            return "This is Index Method" +id;
        }

We can not provide the ref and out parameters to the action method if you try to provide the ref and out parameters to the action method then it will throw an error as follow.
Action Method In MVC 5

Action method can not be overloaded.

 If you try to overload the action method then it will throw an ambiguous error as follows.

Action Method In MVC 5


Type of Action method

  • Action Method
  • Non Action Method

How to call Action Method?

Syntax: YourDomainName/ControllerName/ActionMethodName

Example: localhost/Home/Index
Action Method In MVC 5

How to change default Action Method?

Default Action method is configured in RouteConfig.cs class. By default Action method is the “Index” action method. Change the “Index” action method name as per our requirement as bellow code.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Message", id = UrlParameter.Optional }
            );
        }


You can see the above code we have changed the action method name as “Message” instead of “Index” by default.

How to restrict the public action method in MVC.

To restrict the public action method in MVC. We can use “NonAction” attribute. The “NonAction” attribute exists in System.Web.Mvcnamespace. 

Example of NonAction attribute in ASP.NET MVC:

  [NonAction]
    public string GetFullName(string strFirstName, string strLastName)
    {
            return strFirstName + " " + strLastName;
    }

Default Action Method in MVC: 

Default controller and Action method are configured in RouteConfig.cs class. By default, Controller is the Home controller and default Action method is the “Index” action method.

Example of default action method as follows:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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


Interview questions for freshers on the Action Method,

  1. What is the Action Method in ASP.NET MVC/MVC 5?
  2. How to restrict the Action Method.
  3. How to call Action Method?
  4. How to change default Action Method?
  5. How does the default action get executed?
More detail watch follow video on Action Method in ASP.NET MVC 5:

ASP.NET MVC 5 Tutorials Step By Step:



References:


I hope you understand the concepts of an action method in asp.net MVC 5
Thanks for reading.
Share:

Saturday, March 30, 2019

[Controller In ASP.NET MVC 5]

We will learn Controller in ASP.NET MVC 5 and controller example in ASP.NET MVC 5 in this article.

Controller in ASP.NET MVC 5

Controller in ASP.NET MVC 5

Introduction:

MVC stands for Model, View, and Controller. MVC separates the application into three component like Model, View, and Controller. We will learn Controller in detail. The controller is one of the important components of MVC.


Following are the previews article on ASP.NET MVC

[#1]. What is Controller in ASP.NET MVC 5?

  • The controller can contain action and non-action method.
  • It is used to handle the user request coming from the browser.
  • It will check the request from the browser and identify the action method and return the respective view.
  • A controller is inherited from ControllerBaseclass which is inside the System.Web.Mvcnamespace.
  • While creating controller remember it always suffix as Controllerkeyword.
  • Default Controller is HomeControllerand Indexview.

Following are the steps to create ASP.NET MVC 5 application using Visual Studio 2017

Step 1: 
Open >> [Visual Studio 2017] and go to File >> [New] >> Click on [Project] as follow

Controller in ASP.NET MVC 5



 Step 2: 
Select “ASP.NET Web Application” and provide the meaning full name like “MVCControllerDemo” and Click on “Ok” button.
Controller in ASP.NET MVC 5

 Step 3: 
Select “Empty” template and check the “MVC” checkbox from “New Web Application” window as follow.
Controller in ASP.NET MVC 5

Step 4: 
The default project structure will create as follow.

Controller in ASP.NET MVC 5

[#2]. How to create a controller in MVC 5?

Following Steps will help you to create a controller in ASP.NET MVC 5
 Step 1:
Go to solution explorer Right-click on “Controller” Folder >> Click on [Add] >> click on “Controller” as follow.

Controller in ASP.NET MVC 5


Step 2: 
Select “MVC 5 Empty Controller” from the window and click on “Add” button.

Controller in ASP.NET MVC 5

Step 3:
Provide the meaning full name like “HomeController” and Click on "Add" button.
Controller in ASP.NET MVC 5

Sample code of Controller as follow:

 
using System.Web.Mvc;
namespace MVCControllerDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}


How to check the Controller is inherited from “ControllerBase” class which is inside the “System.Web.Mvc” namespace as follows.

Right-click on "Controller" click on “Go to definition” as follow.
Controller in ASP.NET MVC 5

Controller in ASP.NET MVC 5

How to create a controller with read/write action in MVC 5 using the default template? Or [how to add controller in visual studio 2017]

Step to create a controller with read/write action in MVC 5 as follow 
Step 1:

Go to solution explorer Right-click on “Controller” Folder >> Click on  Add >> click on “Controller” as follow.
Controller in ASP.NET MVC 5

Step 2:
Select "MVC 5 Controller with read/write actions" from the window and click on “Add” button as follow.
Controller in ASP.NET MVC 5

Step 3:
Provide the meaning full name like “ProductController” and Click on “Add” button as follow.
Controller in ASP.NET MVC 5

Default code is generated for "MVC 5 Controller with read/write actions" as follow. without writing a single line of code for our end it will create all action method in the product controller.

using System.Web.Mvc;

namespace MVCControllerDemo.Controllers
{
    public class ProductController : Controller
    {
        // GET: Product
        public ActionResult Index()
        {
            return View();
        }

        // GET: Product/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Product/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Product/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Product/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Product/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Product/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Product/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}



[#4]. How to call controller in MVC 5?

Open any browser and enter the URL like “DomainName/ControllerName” as follow.
Controller in ASP.NET MVC 5

[#5]. How to change the default controller?

Open the Routeconfig.cs file default file looks like as follow.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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



Change the controller name as “Product” controller instead of the “Home” controller as follow.

Controller in ASP.NET MVC 5

[#6]. How the default controller gets executed?


The default controller gets executed based on configuration setting which applied in RouteConfig.cs file. We have provided the “Product” controller as default controller in Routeconfig.cs file. After executing the application default “ProductController” get executed.

[#7]. Flow of Controller in ASP.NET MVC:

Following are the diagrams will help you to understand the flow of ASP.NET MVC Controller.


Controller in ASP.NET MVC 5

As per the above figure, user enters the URL on the browser the given request goes to the server and call the routing which will execute the appropriate controller. And based on request controller execute the appropriate controller action method. It will pass the request to model if the controller action method has data from the database. After completed this controller returns the response to the user.



References:

More detail watch follow video on a controller in asp.net MVC 5:

[ASP.NET MVC 5 tutorial]:

Asp.Net MVC 5 tutorial for beginners in .net c#

Interview Question for fresher:

  • What is controller in ASP.NET MVC/MVC 5?
  • What is the base class of controller?
  • How to change the default controller in ASP.NET MVC / MVC 5?
  • How the default controller gets executed in ASP.NET MVC 5?


I hope you understand the concepts of the controller in asp.net MVC 5 and mvc controller example.
Thanks for reading.

Share:

Sunday, March 24, 2019

Introduction to ASP.NET MVC

We will learn the introduction of ASP.NET MVC and advantages using ASP.NET MVC in this article.

Introduction:
MVC is an architectural design pattern which is used to develop the user interfaces. which will be maintainable, reusable, testable. It is used for separation of concerns.

MVC stands for Model, View, and Controller. MVC separates the application into three component like Model, View, and Controller. We will learn in detail what is Model, View, and Controller.


What is the design pattern?

A design pattern is a solution to the problems that occur in software development.
Design pattern helps us in applications development to resolve problems easily.

Example of design pattern 
  • MVC
  • Proxy
  • Singleton
  • Iterator
  • DAO 

What is ASP.NET MVC:

ASP.NET MVC is a web framework from Microsoft which is used to develop the web application. ASP.NET MVC use MVC architecture pattern. 
ASP.NET MVC are introduced in 2009 by Microsoft.

Advantages of using ASP.NET MVC

  1. Separation of code:

  • This feature is specified separating presentation logic from the database related logic. Easy to develop and modify using this feature.
  • In MVC based application the development process is split into three modules like Model - View - Controller.


2. Loosely coupling:
  • Loosely coupling represents less dependency.
  • Views is mvc are less dependency on models.
  • We can easily edit, expand and enhance the application.


3. Parallel Development:
  • This feature specifies developing models and views parallel.
  • It means multiple programmers work parallel on views and models.
  • This feature makes your application development is faster and easier.


4. Easy to perform unit testing:
  • Unit testing is the concept of testing only a certain portion of the application which is modified.
  • In MVC based application, we can easily perform unit testing.


5. TDD(Test Driven Development):
  • In TDD testers will guide by the development process.
  • MVC application is more comfortable for TDD because It will easy to modify at any point of time and any module.
  • TDD is one of the latest development process using in real time projects.


Model: 
Model is a normal C# class.
Model is responsible to handle data and business logic.
A model represents the shape of the data.
Model is responsible for handling database related changes.

Sample code of model as follow:
namespace MVCDemo.Models

{
    public class Employee

    {
        public int EmpId { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public double Salary { get; set; }
    }
}

View:
A view is responsible for UI(user interface).
View displays the data coming from the model.
A view is an HTML template which will be binding and displaying HTML controls with data.
The “.cshtml” file use the Razor view engine. And .cshtml views are use C# programming.
The view contains the following extension depends on languages.
1. .aspx
2. .asp
3. .html
4. .cshtml
5. .vbhtml
Following are the types of view in ASP.NET MVC -5
1. Layout View
2. Partial view
3. Normal view

Controller:
A controller can contain action and non-action method. It is used to handle the user request coming from the browser. It will check the request from the browser and identify the action method and return the respective view.
A controller is inherited from “ControllerBase” class which is inside the “System.Web.Mvc” namespace.
While creating controller remember it always suffix as “Controller” keyword. Default Controller is “HomeController” and “Index” view.

Sample code of Controller as follow:
 
namespace MVCDemo.Controllers
{
    public class HomeController : Controller
    {
       // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}

Following is the diagram of ASP.NET MVC
what is ASP.NET MVC
                                             Fig. ASP.NET MVC Architecture
ASP.NET MVC
                                      Fig. ASP.NET MVC Architecture

As per the above figure, user request enters the URL on the browser the given request go to the server and call the routing which will execute the appropriate controller. And based on request controller execute the appropriate controller action method. It will pass the request to model if the controller action method has data from the database. After completing this request, the controller returns the response to the user.
Share:

Upcoming Articles/Videos

Design Pattern
SOLID Design Principles
Copyright © Programming With Shri | Powered by Shrimant Telgave Home | Disclaimer | Privacy Policy | Terms and Conditions Design by Shrimant Telgave