How null data is transferred between views and controllers in ASP.NET Core

Is there a function in my controller to check if the user email is active or not?

  
        public async Task<IActionResult>ActiveEmailAccount(EmailActiveAccountViewModel active)
        {
            if (ModelState.IsValid)
            {
                var result = await _userService.ActiveAccount(active);
                
                switch (result)
                {
                    case ActiveEmailResult.Error:
                        ModelState.AddModelError("email", "error");
                        break;

                    case ActiveEmailResult.NotActive:
                        ModelState.AddModelError("email", ""NotActive");
                        break;

                    case ActiveEmailResult.Success:
                        ModelState.AddModelError("email", "active");
                        break;
                }

                ViewData["active"] = result;
                return View(active);
            }
        }
    

This is my repository code:

  
        public async Task<User> GetUserByActiveCode(string activeCode)
        {
            return await _context.Users.FirstOrDefaultAsync(u => u.EmailActiveCode == activeCode);
        }
        
        public async Task<bool> CheckEmailActiveCode(string activeCode)
        {
            return await _context.Users.AnyAsync(u => u.EmailActiveCode == activeCode);
        }
    

In the service, I utilize these repository functions:

  
        public async Task<User> GetUserByActiveCode(string activeCode)
        {
            return await _userRepository.GetUserByActiveCode(activeCode);
        }
        
        public async Task<ActiveEmailResult> ActiveAccount(EmailActiveAccountViewModel active)
        {
            var activeEmailExist=await _userRepository.CheckEmailActiveCode(active.EmailActiveCode);

            var user = await _userRepository.GetUserByActiveCode(active.EmailActiveCode);

            if (activeEmailExist== null )
                return ActiveEmailResult.Error;

            if (activeEmailExist)
            {
                user.UserState = UserState.Active;
                _userRepository.UpdateUser(user);
                await _userRepository.SaveChange();
                return   ActiveEmailResult.Success;
            }
            
            return ActiveEmailResult.NotActive;
        }
    

I receive the active code as a view model in the controller:

 
        public class EmailActiveAccountViewModel
        { 
            public string EmailActiveCode { get; set; }
        }

        public enum ActiveEmailResult
        {
            NotActive,
            Success,
            Error,
        }
    

However, when checking and tracing it with breakpoint, it returns only null. For example, from this URL:

https://localhost:44385/account/ActiveEmailAccount/ddd8915deba74659be3ca89fdc118f14

Why does it return null instead of accepting "ddd8915deba74659be3ca89fdc118f14"?

In the view, I use ViewData to check it and have @model of EmailActiveAccountViewModel:

<div class="alert alert-success"> @ViewData["Active"] </div>

/////Edited////

How can I display these results in separate P tags in the view? Should I use an if statement for that?

Answer №1

When sending the request to activate your email account, be sure to follow this specific format:

https://localhost:44385/account/ActiveEmailAccount?EmailActiveCode=ddd8915deba74659be3ca89fdc118f14
. This will ensure that you are able to successfully receive the value of the EmailActiveAccountViewModel model.

Make sure not to send it like this:

https://localhost:44385/account/ActiveEmailAccount/ddd8915deba74659be3ca89fdc118f14
, as in that case you will not get the desired value.

For more information on how to properly send the request and get the desired result, refer to the following link: https://i.sstatic.net/ozix0.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor checkbox status to trigger confirmation dialog

My goal is to prevent the checkbox from changing if 'NO' is clicked in a dialog. The dialog pops up, but I can't figure out how to wait for it to close before allowing the checkbox change. I've attempted using Promises and doing everyt ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

Even with React.memo(), functional components continue to trigger re-renders

I am facing an issue with my button component that contains a button inside it. The button has a state isActive and a click function passed to it. Upon clicking the button, the isActive flag changes, triggering the app to fetch data accordingly. However, t ...

Tips for building a live React app!

I'm looking to develop a real-time news application that displays a list of countries with the latest news next to each country name, automatically updating as new information is added to the API. For instance, I have an endpoint like this: (for Aust ...

What is the reason for jQuery selector variables not functioning within namespaces?

I'm struggling to figure out why my code isn't working as intended. I'm trying to declare multiple variables, but something seems to be off. Can anyone help me spot the mistake? var message = (function ($) { var $modalBody = $( ...

Unable to log in with SignInManager.SignInAsync (Vue.js Single Page Application)

Encountering some peculiar authentication issues with an app that comprises a dotnet core 2.1 API backend and a Vue.js SPA frontend. All necessary components for logging in and out, including an Auth API controller on the backend, are in place. The fronte ...

What is the process for transferring the "event" object to the functional form of "this.setState()"?

Utilizing the functional form of this.setState() where a function returning an object is passed. When attempting to bind onChange on an input and using this... onInputChange = event => { this.setState(() => ({ ...this.state, [ev ...

Hide the menu by clicking anywhere outside the React component

I'm working on a menu component that needs to close when clicking anywhere on the page while open. Is there a method to achieve this without having to add an event listener to the document and check the event.target? Unfortunately, I cannot send the ...

Converting a PHP multidimensional array to JavaScript

I'm facing an issue with printing data from a PHP array in a JavaScript function. The current setup is not producing the desired outcome. Here's how the data is being processed in PHP: $daten = array(); $anzahl = array(); $leads = array(); if ($ ...

Mechanism for enhancing and modifying capabilities of an object through a design pattern

TL:DR design pattern for objects that temporarily modify each other in a game scenario. Functionality is added and then removed dynamically. As a database developer delving into front-end development, I am exploring new techniques to stay informed about v ...

Can you explain the meaning behind this code snippet using spread syntax, the .map method, and .dataset.filter?

I'm currently dissecting this code snippet to understand its functionality. I am particularly puzzled by the use of spread syntax (...document.querySelectorAll) and the purpose of the .map and .dataset.filter methods. const filters = [...document.quer ...

How to modify the placeholder attribute value using jQuery

i have a table $(document).ready(function() { $('#f05_0002').change(function() { if ($("#f05_0002").val() == "OFF TRACK") { $("#f06_0002").attr("placeholder", "Please specify what has not been achieved and provide recommenda ...

Creating a Component and Programmatically Returning a Value in Vue.js: A Step-by-Step Guide

Could you assist me in solving my issue? I am looking to develop a customized plugin for my project so that my team and I can easily implement an alert component without having to design the dialog box repeatedly on every page and vuejs file. My objective ...

Executing a webservice method in an html page using javascript without the need to refresh the page

Is it possible to call a webservice from an index.html page using JavaScript? My webservice is located at "localhost/ws/service.asmx" and the specific web method I want to call is called HelloWorld. The index.html page contains an HTML submit button whic ...

The Reactjs infinite scroll feature continuously displays fresh data

Every time I scroll, my data is always rendering on page 2 and page 1 disappears, and the items.concat function is not working properly. My fetch data code looks like this: const FetchUrl = async (p) =>{ const Url = await fetch(`api-link=${p}`); ...

An error of TypeError is being encountered in AngularJS

Hello, I am new to creating mobile apps with Ionic and Angular. Currently, I have a simple login form and a corresponding login button that triggers a controller. Here is the code snippet for the controller: angular.module('starter.controllers', ...

Is it possible to utilize the default error handling page rather than a specific view for expressing

Currently, I'm going through a tutorial on MDN Express for building a "Local Library" application that utilizes Pug (Jade) as its templating engine. In this segment of the tutorial, it explains the process of creating a controller to manage a form POS ...

When I assign my welcome channel ID to MongoDB, I notice that the last two digits always seem to change

Why does the last two digits of my channel ID change to "00" when I try to set my welcome channel ID to MongoDB? For example: 954226649841430572 --> (when sent to database) 954226649841430500 https://i.sstatic.net/blLIL.png Here's my code: await ...

What could be the reason I am unable to choose data properties from the dropdown options?

There are two different dropdowns for clothing types and colors. When a type of clothing is selected from the first dropdown, JSON data will fill the second dropdown with options based on the first dropdown selection. After selecting an option from the se ...

How can we set up a Vue.js component before incorporating it into a template?

Currently, I am working on a Vue single file template where I need to fetch some data (a JWT token) and then use that token to make another request to a graphql endpoint. The Provider Component in my template requires the JWT Token to be set up with the ...