Problem with controllers and routing using asp.net core

Im new to asp.net Core and i've stumbled upon problem with my routing/Controller. Not sure which one is faulty. Overall I don't know how to set up multiple controllers for multiple .cshtml files which will allow me to move between pages or do simple CRUD operations. I've created standard Web application project. My Project schema looks like on picture before.

RegisterViewController (Should work with RegisterView):

using Microsoft.AspNetCore.Mvc;
using QSwapper__Aplikacja_do_wymiany_rzeczy.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QSwapper__Aplikacja_do_wymiany_rzeczy.Controllers
{
    [Route("Forms")]
    public class RegisterViewController : Controller
    {

        private QSwapperDataContext db = new QSwapperDataContext();

        [Route("")]
        [Route("LoginView")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [Route("RegisterView")]
        public IActionResult RegisterView(UserInfo userinfo)
        {
            db.UserInfos.Add(userinfo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


    }
}

MainController (Supposed to work with Index, mainly going to work with movement and loading few datas from database):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QSwapper__Aplikacja_do_wymiany_rzeczy.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

    }
}

RegisterView.cshtml code:

@page
@model App.Models.UserInfo
@{
    ViewData["Title"] = "Sign up";
    Layout = null;
}
<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Rejestracja</title>
    <meta name="description" content="Register">
    <link rel="stylesheet" href="/css/Register.css">
</head>
<body>
    <div class="blurred-box">
        <div class="user-login-box">
            <span class="user-icon"></span>
            <div class="user-name">
                <form method="post" asp-controller="RegisterView" asp-action="RegisterView">
                    <div class="section">
                        <input class="user-register" type="text" placeholder="Login" asp-for="UserLogin"/>
                        <input class="user-register" type="password" placeholder="Password" asp-for="UserPassword"/>
                        <input class="user-register" type="text" placeholder="Name" asp-for="UserName"/>
                        <input class="user-register" type="text" placeholder="Surname" asp-for="UserSurname"/>
                        <input class="user-register" type="email" placeholder="email" asp-for="UserEmail"/>
                    </div>
                    <div class="section">
                        <input class="user-register" type="text" placeholder="adress" asp-for="UserAdress" />
                        <input class="user-register" type="text" placeholder="city" asp-for="UserCity" />
                        <input class="user-register" type="text" placeholder="PostalCode" asp-for="UserPostalCode" />
                        <input class="user-register" type="text" placeholder="Contact Number" asp-for="UserContact" />
                    </div>
                    </form>
            </div>
            <input class="user-button" type="submit" value=">"/>
        </div>
    </div>
</body>
</html>

Startup routing part (ofc added services.AddMvc(); ):

        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

When im trying to change that part to:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseRouting();
            app.UseCors();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=UserInfo}/{action=Index}");
            });
        }

Im getting error: [![Error screen][1]][1]

Also my [![Project Schema][2]][2] can be found on this screenshot.

Basicly i have 0 errors in my code just it doesn't work. It look like controllers doesn't work at all or rather they aren't used by files. Im completly green with Routing and stuff so idk how to fix it so I can make those controllers working and add new controllers for another cshtml files.

Thanks in advance and sorry for the problem. If there's additional info needed i will provide it as soon as possible. Hope someone can help me. Im a bit dumb so if u can explain fix step by step if possible i would be grateful.

@Edit Overall my problem is controllers not working or rather even when i assigned action it doesn't work at all like below.

HomeController:

namespace QSwapper__Aplikacja_do_wymiany_rzeczy.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult SignIn()
        {
            return View("/Forms/LoginView");
        }


    }

_Layout fragment code where i invoke signin action (There's nothing above <!DOCTYPE>)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/css/site.css" />
</head>
<body>
    <header>
        <div id="mainWrapper">
            <!-- Contains Logo and links -->
            <div id="logo">
                <img src="file:///Users/trishaolalia/Desktop/hanah_olalia_site/shoe-logo.pdf" alt="sample logo">
            </div>
            <div id="headerLinks">
                <input type="text" id="search" value="search">
                <a asp-controller="Home" asp-action="" title="Login">Logowanie</a>
                <a href="/Forms/RegisterView" title="Register">Rejestracja</a>
            </div>

AND STARTUP routing im using:

 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

@edit2 FormsController- working with RegisterView

    {

        private QSwapperDataContext db = new QSwapperDataContext();

        [HttpGet]
        public IActionResult RegisterView()
        {
            return View();
        }


        [HttpPost]
        public IActionResult RegisterView(UserInfo userinfo)
        {
            db.UserInfos.Add(userinfo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


    }
}```


as for .cshtml code for RegisterView it stays the same. Overall there's no action at all. It doesn't save to database or redirect to Index Page



  [1]: https://i.stack.imgur.com/C3J30.png
  [2]: https://i.stack.imgur.com/l3hg1.png

1 answer

  • answered 2021-01-17 07:12 caroline mwasigala

    The view takes the name of the action so what you need to do is to add an action name attribute

    [ActionName("LoginView")]
    

    Your startup configuration of controller should be

    services.AddControllersWithViews().AddRazorOptions(options => {
                
                options.ViewLocationFormats.Add("/Views/Forms/{0}.cshtml");
    
          });