Home > Software engineering >  Can't get values ​entered in ASP.NET MVC Form
Can't get values ​entered in ASP.NET MVC Form

Time:07-30

First of all my codes:

ManageClass.cshtml:

@{
    ViewData["Title"] = "Class' Management";
}

<br />
<h2>Add Class</h2>

<form method="post" asp-controller="AddClassDB" asp-action="">
<div >
  <div >
    </div> </div>
    <label for="formGroupExampleInput2">Class Name</label>
    <input type="text"  id="classNameInput">
  <br/>
  <div >
      <button type="submit" >Add</button>
  </div>
  <br />
  <h2>Manage Class</h2>
</form>

HomeController.cs:

using Microsoft.AspNetCore.Mvc;
using StudentWeb.Models;
using System.Diagnostics;

namespace StudentWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }
        public ActionResult ManageClass()
        {
            return View();
        }
        public ActionResult AddClassDB(ClassTable _table)
        {
            Console.WriteLine(_table);
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

I will take the value of classNameInput in ManageClass.cshtml and save it to SQL. I will do the saving in the Controller, but I have not yet received the value entered by the user.

But after I enter the value in the input and press the submit button, I get the following result:

enter image description here

enter image description here (page not found)

CodePudding user response:

You are using the wrong value for asp-controller and asp-ation for the form. Hence it generates the wrong action path for the form.

It should be:

<form method="post" asp-controller="Home" asp-action="AddClassDB">
 ...
</form>

By default, all the action methods in the controller are GET (method). You need to apply [HttpPost] attribute so that the AddClassDB is recognized as POST (method).

[HttpPost("AddClassDB")]
public ActionResult AddClassDB(ClassTable _table)
{
    Console.WriteLine(_table);
   
    // TO-DO Redirect to view that is existed
    return View();
}
  • Related