0
votes

I'm trying to make a registry system. I need to access the values ​​entered by the user from Inputs. I made a controller for this.

My codes:

addClass.cshtml:

@page
@model AddClassPage
@{
    ViewData["Title"] = "Add Student";
}
@using (Html.BeginForm()) ;

<div class="p-3 mb-2 bg-dark text-white">
    <h2 class="display-4">Add Class</h2>
</div>
<form>
  <div class="form-group">
    <label for="teacherIdInput">Class ID (number only):</label>
    <input type="number" class="form-control" min="0" name="classId" placeholder="Class ID">
  </div>
  <div class="form-group">
    <label for="teacherNameInput">Class Name:</label>
    <input type="text" class="form-control" name="className" placeholder="Class Name">
  </div>
  <button type="submit" class="btn btn-success" name="addButton">Add</button>
</form>

<div>
</div>

AddClassController.cs:

using Microsoft.AspNetCore.Mvc;
using System;

namespace StudentWebAppController {
    public class AddClassController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(int classId, string className)
        {
            return View();
        }

    }
}

I've been coding watching a video on YouTube and I've coded exactly the same. But it's not working for me.

After sumbiting from the site:

enter image description here

As you can see, the value entered by the user after sumbiting from the site is not passed into the argument. But in the video I watched, it is transmitted and the value entered by the user can be accessed. What's wrong with my code?

2
Check the form tags, you probably have two. And you probably need action and method tags also. Like <form action="/Controller/Method" method="Post"> - MonkeyDLuffy
And check the video again, your code is different from the video :) @@using (Html.BeginForm()) {htmlCode} - MonkeyDLuffy

2 Answers

1
votes

Change the view code to this :

@model AddClassPage
@{
    ViewData["Title"] = "Add Student";
 }


<div class="p-3 mb-2 bg-dark text-white">
    <h2 class="display-4">Add Class</h2>
</div>

@using (Html.BeginForm(FormMethod.Post, "Index", "AddClass", "AddClass")) {
  <div class="form-group">
    <label for="teacherIdInput">Class ID (number only):</label>
    <input type="number" class="form-control" min="0" name="classId" placeholder="Class ID">
  </div>
  <div class="form-group">
    <label for="teacherNameInput">Class Name:</label>
    <input type="text" class="form-control" name="className" placeholder="Class Name">
  </div>
  <button type="submit" class="btn btn-success" name="addButton">Add</button>
}
0
votes

Add action to your form so it become

<form action="/ControllerName/MethodName" method="POST">