0

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
Luke
  • 11
  • 6
  • What is the URL in the browser? – mjwills Jan 17 '21 at 02:37
  • `return View()` in Index action of `RegisterViewController` looks for view with name Index in RegisterView folder. And if not found it will look in shared folder. In your case Index.cshtml does not exist in both of these locations. That's why you are getting this error. – Chetan Jan 17 '21 at 02:47
  • @ChetanRanpariya Okay. I understand that but even in HomeController when i wrote simple action to move to another View. ``` public IActionResult SignIn() { return View(/Forms/LoginView); }``` and ofc used asp-controll="Home" asp-action="SingIn" in my HTML it didn't move to another view. It looked like returning Index. – Luke Jan 17 '21 at 08:43
  • you mean `return View(/Forms/LoginView);` returned Index view of Home Controller? Can you update the question with the latest code? – Chetan Jan 17 '21 at 09:06
  • @ChetanRanpariya Done. Added those parts below ~edit. Thanks a lot for your help – Luke Jan 17 '21 at 10:31

1 Answers1

0

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");

      });
  • Sorry but it doesn't help. Controllers aren't working at all sadly. Its like they do not even work. Can't even returin View("LoginView"); – Luke Jan 17 '21 at 10:54
  • You need to configure View location formatter in your startup file. I have edited the answer to include the configuration. The leave return View() as it is – Caroline Mwasigala Jan 17 '21 at 13:10
  • It looks like to helped a bit. Now i have some error with Null so can't see if it finally works but looks like it does for now – Luke Jan 17 '21 at 13:23
  • I fixed the problem. Had to remove ~Page from my code. Overall now the problem is that RegisterView is opened as main window, not Index and controller doesn't seem to be working. Part of RegisterView where im submitting data doesn't work or rather there's no action on submit button. – Luke Jan 17 '21 at 13:35
  • What do you mean by main window? – Caroline Mwasigala Jan 17 '21 at 13:39
  • Now as my home Page RegisterView is opening which isn't working sadly – Luke Jan 17 '21 at 13:43
  • If you don't want to be the main window `options.ViewLocationFormats.Add("/Views/Forms/{1}{0}.cshtml");` For more information visit [link] (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.razor.razorviewengineoptions.viewlocationformats?view=aspnetcore-3.1) – Caroline Mwasigala Jan 17 '21 at 13:52
  • @Caroline.mwasigala Well regardless of main window Controller doesn't seem to be working. It doesn't add my form to database nor even redirect to IndexPage ;x I posted it in main post as ~edit2 – Luke Jan 17 '21 at 14:03
  • @Luke can you show me how you do your redirection – Caroline Mwasigala Jan 17 '21 at 14:26
  • I posted it in edit2. Using redirecttoaction("Index"). Also tried return View("Index") but didn't work. Overall it doesn't even submit data to database ;x – Luke Jan 17 '21 at 14:35
  • @Luke There is no action index remember we changed the action name to LoginView – Caroline Mwasigala Jan 17 '21 at 15:07
  • I remember that. Fixed my code a bit thanks to your tips and advices! It works now :D Didn't notice somehow i posted submit after . Well thanks to your help my controller started working with page so thanks a lot! :D – Luke Jan 17 '21 at 15:31
  • @Luke thanks for your appreciation. You are warmly welcomed – Caroline Mwasigala Jan 17 '21 at 15:38