Details About MVC

Model-View-Controller By Sagar Jaybhay

MVC stands for model view and controller and when client or browser issues a request then it comes to controller first. Then on the basis of requirement controller decide should he called view only or call model and then view.

How to enable MVC in the blank template?

To enable this you need to AddMvc() method in Configureservice method. This is done by dependency injection. There are 2 types of method one is AddMvc() and another is AddMvcCore() method. To enable this we need to use AddMvc() method.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

So to add MVCmiddleware in request processing pipeline you need to add this Configure method in startup class. But there are 2 methods to enable MVC middleware UseMVC() and other is UseMvcWithDefaultRoute().

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();          

            app.Run(async (context) =>
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }

So from above, we get an idea about if we want to add MVC in blank template fro that there are 2 step process. First addmvc()  in dependency injection in configure method and then use MVC middleware in MVC pipeline.

What is the difference between AddMvc() and AddMvcCore() method?

AddMvc() Method

Is a complete bundle of package. Below method shows that internally it is called AddMvcCore method. Other things are that it also includes a razor view engine, formatters, authorizations, data annotations like that. So if you include this complete sets of services get default added for use of MVC.

public static IMvcBuilder AddMvc(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    var builder = services.AddMvcCore();

    builder.AddApiExplorer();
    builder.AddAuthorization();

    AddDefaultFrameworkParts(builder.PartManager);

    // Order added affects options setup order

    // Default framework order
    builder.AddFormatterMappings();
    builder.AddViews();
    builder.AddRazorViewEngine();
    builder.AddCacheTagHelper();

    // +1 order
    builder.AddDataAnnotations(); // +1 order

    // +10 order
    builder.AddJsonFormatters();

    builder.AddCors();

    return new MvcBuilder(builder.Services, builder.PartManager);
}

AddMvcCore() Method

Now second is AddMvcCore() method it includes some basic functionality and if you need formatting or other stuff like that you need to include or add dependencies in configure package methods. Below is the code of that method.

public static IMvcCoreBuilder AddMvcCore(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    var partManager = GetApplicationPartManager(services);
    services.TryAddSingleton(partManager);

    ConfigureDefaultFeatureProviders(partManager);
    ConfigureDefaultServices(services);
    AddMvcCoreServices(services);

    var builder = new MvcCoreBuilder(services, partManager);

    return builder;
}

So this method is small and added only some basic functionality to start with. But both method returns IMvcCoreBuilder. In this AddMvcCoreServices(services) this will add really simple services which isFileContents, RedirectToRouteResults, ActionResolvers, use Controllers, use routing like that.

Model In Asp.Net core:

It Is classes that manage the data and process that data and display that data. It is one or more classes. In Controller class Json is not present but it Is present In Controller class. In MVC core Interface are used for dependency injection.

Error: InvalidOperationException: Unable to resolve service for type 'LearnAspCore.Models.IStudentRepository' while attempting to activate 'LearnAspCore.Controller.HomeController'.

In below code, you can find we pass the repository interface object in the constructor.

public class HomeController : Controller
    {
        private IStudentRepository _repository;

        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }
}

but we never create an instance of that interface means, in reality, we need to pass an object of StudentRepository class in which we implement the interface but we didn’t create that object and we want to inject that object in the constructor so that’s why it throws an error.

Below is student repository class.

public class StudentRepo : IStudentRepository
    {
        private List<Student> _students;

        public StudentRepo()
        {
            _students = new List<Student>() {
                new Student(){ Address="xyz",Division="B", FullName="Sagar",StudentId=1},
                new Student(){ Address="abc",Division="C", FullName="RAM",StudentId=2},
                new Student(){ Address="def",Division="A", FullName="LAKHAN",StudentId=3}
            };
        }
        

        public Student GetStudents(int StudentID)
        {
            return _students.Where(r=>r.StudentId==StudentID).FirstOrDefault();
        }
    }

For Dependency injection in ASP. NET core we need to register our dependency in this. For this, we need to register this with the dependency injection container. So for that, we use AddSingleton() method.

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton<IStudentRepository,StudentRepo>();
        }

In above method which is part of startup class we use that to register our dependency. The use of the singleton method as a name suggests it will use to creating a single object or singleton service throughout the application lifetime and the instance will create at the first time application run. There are also other 2 methods AddTransient() and AddScoped(). Asp.net core has built-in support for dependency injection.

Controller

What is Controller and what are functions of that controller in Asp.Net core?

In Asp.net MVC controller name always suffix with Controller keyword. This controller inherits from Controller class. Below is the code for the controller.

public class HomeController: Controller
    {
        private IStudentRepository _repository;

        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }
        public JsonResult Index()
        {
            return new JsonResult(_repository.GetStudents(1));
            //return new JsonResult(new { ID=1,Name="sagar"});
        }
    }

When browser issues a request it comes to MVC controller first and these controller has bunch of public methods. By Using routing module the url are matched with mvc controller and action methods. To coup with content negotiation, we need to use return type ObjectResult.

public ObjectResult Index()
        {
            Student student = _repository.GetStudents(1);
            return new ObjectResult(student);           
        }

View In MVC controller?

In MVC view is the display entity which we saw on a web browser. Normally view has .cshtml ,.vbhtml extensions. All the views belong to that controller are present in the controller names folder means in our Home controller and view belong to that controller are present in the home folder.

View is Html template with embedded Razor markup in that.

public ViewResult Details()
        {
            Student student = _repository.GetStudents(1);
            return View(student);
        }
COntroller with view

View Discovery Mechanism in Asp.Net Core. If you want to render view from another location then you need to use an absolute path in that view method as below.

public ViewResult Details()
        {
            Student student = _repository.GetStudents(1);
            return View("folderName/fileName.cshtml",student);
        }

You can also use a relative path if the folder is present in that Views folder then use below syntax.

public ViewResult Details()
        {
            Student student = _repository.GetStudents(1);
            return View("../folderName/fileName",student);
        }

In this relative path no need to specify file extension. When MVC search for view it will search for a file of the same name as the action name in the respective controller folder name. You can pass the custom view name to view. File path can be absolute or relative.

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts