Call Controller Method from View In ASP.NET Core MVC C#

Hello Guys, I hope you are doing well. TodayΒ  i’mΒ  going to show you how can we use controller method in view.

The reason behind this blog is sometimes i had to use some method for string modification and instead of creating another service or helper

class i want to create that method in controller and used it in view.

Prerequisite

  • Basic knowledge of C# .NET Core MVC

Now, here we gonna create a new .NET Core MVC Web Application.

Here, You can see that I’ve created a simple project.

Now, Create AddHelloWorld static method in HomeController.

using BlogMVCController.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace BlogMVCController.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public static string AddHelloWorld(string data) {
            string newString = data + " Hello World";
            return newString;
        }
    }
}

Apply some code to it. Now in Home view aka Index view, we have to use this method and it’s all about the blog.

For that making happen, in view give Reference to a namespace that contains HomeController. Like this,

Now, the method we are calling is static so just call it by class name, no need to initialize the object for that.

@using BlogMVCController.Controllers;

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    @{ 
        <div class="container text-center">
            <h4 class="text-primary">This string will be append by this method @HomeController.AddHelloWorld("Hello ")</h4>
        </div>
    }
    

</div>

Now, the last result looks like this.

I hope you guys will like my blog and you will get an idea about this stuff.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories