skip to Main Content

I wanted to fetch a key from appsettings.json file to javascript code in .net 8 MVC project.

i have added the key in appsetting.json in the below manner.
appsettings.json

{
"RequestCountlimit": "10"
}

Please let me know how to fetch the values from appsettings.json

2

Answers


  1. If you want to get the appsetting.json value inside the js in MVC, you should firstly get it from the backend and then pass it to the view to get it.

    More details, you could refer to below example:

        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly IConfiguration _configuration;
        
            public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
            {
                _logger = logger;
                _configuration = configuration;
            }
        
            public IActionResult Index()
            {
                var requestCountLimit = _configuration["RequestCountlimit"];
        
                // Pass the value to the view using ViewData
                ViewData["RequestCountLimit"] = requestCountLimit;
                return View();
            }
    
    }
    

    View:

    @section Scripts{
    
    
    
        <script type="text/javascript">
            // Fetch the value from ViewData and embed it into JavaScript
            var requestCountLimit = '@ViewData["RequestCountLimit"]';
            console.log("Request Count Limit: " + requestCountLimit);
     
        </script>
    
    }
    

    Result:

    enter image description here

    Login or Signup to reply.
  2. References : https://learn.microsoft.com/en-us/aspnet/core/mvc/views/dependency-injection?view=aspnetcore-8.0

    You can use Dependency injection to get appsetting.json values in view.

    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration
    
    <script type="text/javascript">
        const RequestCountlimit = '@Configuration["RequestCountlimit"]';
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search