简体   繁体   中英

Can't get values ​entered in ASP.NET MVC Form

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 class="container">
  <div class="form-group">
    </div> </div>
    <label for="formGroupExampleInput2">Class Name</label>
    <input type="text" class="form-control" id="classNameInput">
  <br/>
  <div class="float-right">
      <button type="submit" class="btn btn-success">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:

在此处输入图像描述

在此处输入图像描述 (page not found)

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM