提交按钮未在 ASP.NET MVC Web 应用程序中触发
Posted
技术标签:
【中文标题】提交按钮未在 ASP.NET MVC Web 应用程序中触发【英文标题】:Submit button is not firing in ASP.NET MVC web application 【发布时间】:2021-11-05 19:02:03 【问题描述】:我是 ASP.NET 和 C# 的新手,通过查看一些教程,我尝试创建一个投票站点,但提交按钮根本不起作用,已经尝试了这里给出的所有解决方案,但现在它仍然不起作用.
家庭控制器:
namespace test.Controllers
public class HomeController : Controller
[HttpGet]
public ActionResult Index()
return View();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult voted(Vote_Results Vote, string Hafiza, string Mridul, string Ranvir, string Sayan, string Sourav, string Shusovan)
string message = "";
//Model Validation
if (ModelState.IsValid)
#region Email Existance
var isExist = IsEmailExist(Vote.Email_Id);
if (isExist)
ModelState.AddModelError("EmailExist", "Candidate has Already Voted!");
return View(Vote);
#endregion
#region binding extra property
if (Hafiza == "true")
Vote.Hafiza_Khatun = true;
else
Vote.Hafiza_Khatun = false;
if (Mridul == "true")
Vote.Mridul_Bose = true;
else
Vote.Mridul_Bose = false;
if (Ranvir == "true")
Vote.Ranvir_Baral = true;
else
Vote.Ranvir_Baral = false;
if (Sourav == "true")
Vote.Sourav_Kr_Halder = true;
else
Vote.Sourav_Kr_Halder = false;
if (Shusovan == "true")
Vote.Shusovan_Chakraborty = true;
else
Vote.Shusovan_Chakraborty = false;
if (Sayan == "true")
Vote.Sayan_Parui = true;
else
Vote.Sayan_Parui = false;
Vote.is_voted = true;
Vote.TimeStamp = DateTime.Now;
#endregion
#region save data to database
using (PR_Vote_21Entities db = new PR_Vote_21Entities())
db.Vote_Results.Add(Vote);
db.SaveChanges();
//send Email to user
SendConfirmationEmail(Vote.Email_Id, Vote.Name);
message = Vote.Name + ",<br>Your Responce Has been submited SUCCESSFULLY!<br>" + "You will recieve an Email Shortly!";
Response.Write(message);
//Logout();
#endregion
else
message = "Invalid Request";
Response.Write(message);
return View();
[NonAction]
public bool IsEmailExist(string emailID)
using (PR_Vote_21Entities dc = new PR_Vote_21Entities())
var v = dc.Vote_Results.Where(a => a.Email_Id == emailID).FirstOrDefault();
return v != null;
[NonAction]
public void SendConfirmationEmail(string emailID, string Name)
var fromEmail = new MailAddress("email@domain.com", "name");
var toEmail = new MailAddress(emailID);
var fromEmailPassword = "PW";
string subject = "Your vote is successfully submited!";
string body = "<div> Hi," + Name + "<br><br> Your response has been submitted successfully.<br>" + "Thank you <br><br> Do Not Replay, It is an autogenerated Mail <br> DEE | PRSV </div>";
var smtp = new SmtpClientHost = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword);
using (var message = new MailMessage(fromEmail, toEmail)
Subject = subject, Body = body, IsBodyhtml = true)
smtp.Send(message);
HTML 页面:
@model test.Models.Vote_Results
@
Layout = null;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.87.0">
<title> PRV-DEE</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/jumbotron/">
<!-- Bootstrap core CSS -->
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<!-- Favicons -->
<link rel="icon" href="~/Assets/TitleImg.png" />
<meta name="theme-color" content="#7952b3">
<style>
.bd-placeholder-img
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
@@media (min-width: 768px)
.bd-placeholder-img-lg
font-size: 3.5rem;
.Candidate
font-size: 20px;
.big-checkbox
width: 20px;
height: 20px;
.hide
display: none;
</style>
<!--Special Scripts-->
<script src="../Assets/votesite.js"></script>
</head>
<body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<main>
<div class="container py-4">
<header class="pb-3 mb-4 border-bottom">
<a href="/" class="d-flex align-items-center text-dark text-decoration-none">
<img src="~/Assets/TitleImg.png" >
<span class="fs-4"> PR SELECTION</span>
</a>
</header>
<div class="p-5 mb-4 bg-light rounded-3">
<div class="container-fluid py-5">
<h1 class="display-5 fw-bold" style="color:#03b603;">RULES </h1>
<ol class="col-md-12 fs-5">
<li>No 2nd vote will be taken, If a 2nd vote is found in someone's name his/her vote will be canceled.</li>
<li>If someone is found to be cheating he will be disqualified from voting.</li>
<li>Don't Share your <b>Password</b> and <b>DOB</b> with anyone until the voting process is completed.</li>
<li>Strictly 3 Candidates must be chosen from the list.</li>
<li>Don't share your voting config with others.</li>
</ol>
<div class="form-check" style="margin-top: 30px;">
<input class="form-check-input" type="checkbox" value="" id="agree" onclick="visible()">
<label class="form-check-label" for="flexCheckDefault">
I Agree with Above Rules
</label>
</div>
</div>
</div>
@using (Html.BeginForm("voted", "Home", FormMethod.Post))
@Html.AntiForgeryToken()
<div class="row align-items-md-stretch hide" id="P-Details">
<div class="col-md-6">
<div class="h-100 p-5 bg-dark rounded-3">
<h2 class="text-white">Insert Your Details</h2>
<div class="form-floating mb-3">
@Html.EditorFor(model => model.Reg_No, new htmlAttributes = new @type = "text", @class = "form-control", @id = "Reg", @placeholder = "D123456789", @onchange = "count()" )
@Html.ValidationMessageFor(model => model.Reg_No, "", new @class = "text-danger" )
@*<input type="text" class="form-control" id="Reg" placeholder="D123456789" onchange="count()">*@
<label for="Reg">Registration No</label>
</div>
<div class="form-floating">
@Html.EditorFor(model => model.DOB, new htmlAttributes = new @type = "date", @class = "form-control", @id = "DOB", @placeholder = "07-Sep-2021", @onchange = "count()" )
@Html.ValidationMessageFor(model => model.DOB, "", new @class = "text-danger" )
@*<input type="date" class="form-control" id="DOB" placeholder="07-Sep-2021" onchange="count()">*@
<label for="floatingInputValue" color="red">Date Of Birth</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="h-100 p-5 bg-light border rounded-3">
<h2>Non-Changable Details</h2>
<form>
<div class="form-floating">
@Html.EditorFor(model => model.Email_Id, new htmlAttributes = new @type = "text", @class = "form-control", @id = "Email", @placeholder = "name@example.com", @Value = "name", @disabled = "disabled" )
@Html.ValidationMessageFor(model => model.Email_Id, "", new @class = "text-danger" )
@*<input type="text" class="form-control" id="floatingInputValue" placeholder="name@example.com" value="koustavshee.work@gmail.com" disabled>*@
<label for="floatingInputValue">E-mail address</label>
</div>
<div class="form-floating" style=" margin-top:5px">
@Html.EditorFor(model => model.Name, new htmlAttributes = new @type = "text", @class = "form-control", @id = "fullName", @placeholder = "example Name", @Value = "name@domain.com", @disabled = "disabled" )
@Html.ValidationMessageFor(model => model.Name, "", new @class = "text-danger" )
@*<input type="text" class="form-control" id="floatingInputValue" placeholder="example Name" value="Koustav Shee" disabled>*@
<label for="floatingInputValue">Full Name</label>
</div>
</form>
</div>
</div>
</div>
<div class="p-5 mb-4 bg-light rounded-3 hide" style="margin-top:20px" id="Candidates">
<div class="container-fluid py-5">
<h1 class="display-5 fw-bold" style="color:#03b603; margin-bottom:20px">PR Candidates</h1>
<div class="row">
<div class="form-check col" style="margin-top: 10px;">
@Html.CheckBox("Hafiza", false, new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can1", @onclick = "count()" )
@*@Html.EditorFor(model => model.Hafiza_Khatun, new htmlAttributes = new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can3", @onclick = "count()", @Value = "" )*@
<label class="form-check-label Candidate" for="flexCheckDefault">
Hafiza_cc
</label>
</div>
<div class="form-check col" style="margin-top: 10px;">
@Html.CheckBox("Mridul", false, new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can2", @onclick = "count()" )
@*<input class="form-check-input big-checkbox" type="checkbox" value="" id="can2" onclick="count()">*@
<label class="form-check-label Candidate" for="flexCheckDefault">
Mridul_cc
</label>
</div>
</div>
<div class="row">
<div class="form-check col" style="margin-top: 10px;">
@Html.CheckBox("Ranvir", false, new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can3", @onclick = "count()" )
@*<input class="form-check-input big-checkbox" type="checkbox" value="" id="can3" onclick="count()">*@
<label class="form-check-label Candidate" for="flexCheckDefault">
Ranvir_cc
</label>
</div>
<div class="form-check col" style="margin-top: 10px;">
@Html.CheckBox("Sayan", false, new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can4", @onclick = "count()" )
@*<input class="form-check-input big-checkbox" type="checkbox" value="" id="can4" onclick="count()">*@
<label class="form-check-label Candidate" for="flexCheckDefault">
Sayan_cc
</label>
</div>
</div>
<div class="row">
<div class="form-check col" style="margin-top: 10px;">
@Html.CheckBox("Sourav", false, new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can5", @onclick = "count()" )
@*<input class="form-check-input big-checkbox" type="checkbox" value="" id="can5" onclick="count()">*@
<label class="form-check-label Candidate" for="flexCheckDefault">
Sourav_cc
</label>
</div>
<div class="form-check col" style="margin-top: 10px;">
@Html.CheckBox("Shusovan", false, new @class = "form-check-input big-checkbox", @type = "checkbox", @id = "can6", @onclick = "count()" )
@*<input class="form-check-input big-checkbox" type="checkbox" value="" id="can6" onclick="count()">*@
<label class="form-check-label Candidate" for="flexCheckDefault">
Shusovan_cc
</label>
</div>
</div>
<br />
<div class="d-grid gap-2 d-md-flex justify-content-md-end">
<button class="btn btn-primary me-md-2" type="submit" id="submit"
disabled>
Submit Responce
</button>
</div>
</div>
</div>
<footer class="pt-3 mt-4 text-muted border-top">
institution | Department
</footer>
</div>
</main>
</body>
</html>
为了数据验证,我在另一个名为扩展的文件夹中使用了它,并从命名空间中删除了文件夹名称
using System.ComponentModel.DataAnnotations;
namespace test.Models
[MetadataType(typeof(Vote_ResultsMetaData))]
public partial class Vote_Results
public class Vote_ResultsMetaData
[Display(Name = "Email ID")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Email Address Required")]
[DataType(DataType.EmailAddress)]
public string Email_Id
get;
set;
[Display(Name = "Name")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name Required")]
[DataType(DataType.Text)]
public string Name
get;
set;
[Display(Name = "Reg No")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Registation No Required")]
[MinLength(10, ErrorMessage = "Reg No is of 10 Characters")]
[MaxLength(10, ErrorMessage = "Reg No is of 10 Characters")]
[DataType(DataType.Text)]
public string Reg_No
get;
set;
[Display(Name = "DOB")]
[Required(AllowEmptyStrings = false, ErrorMessage = "DOB Required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "0:mm-dd-yyyy")]
public System.DateTime DOB
get;
set;
Entity Framework 生成的实际类:
namespace test.Models
using System;
using System.Collections.Generic;
public partial class Vote_Results
public int pk_id get; set;
public string Email_Id get; set;
public string Name get; set;
public string Reg_No get; set;
public System.DateTime DOB get; set;
public Nullable<bool> Hafiza_Khatun get; set;
public Nullable<bool> Mridul_Bose get; set;
public Nullable<bool> Ranvir_Baral get; set;
public Nullable<bool> Saikat_Naskar get; set;
public Nullable<bool> Sayan_Parui get; set;
public Nullable<bool> Sourav_Kr_Halder get; set;
public Nullable<bool> Shusovan_Chakraborty get; set;
public bool is_voted get; set;
public System.DateTime TimeStamp get; set;
用于添加一些动作的javascript文件:
function visible()
element = document.getElementById('agree')
if (element.checked == true)
document.getElementById('P-Details').classList.remove('hide')
document.getElementById('Candidates').classList.remove('hide')
else
document.getElementById('P-Details').classList.add('hide')
document.getElementById('Candidates').classList.add('hide')
function count()
var idArr = ['can1', 'can2', 'can3', 'can4', 'can5', 'can6']
var inpArr = ['Reg', 'DOB']
var N0 = 0
var N1 = 0
for (var i = 0; i < idArr.length; i++)
if (document.getElementById(idArr[i]).checked == true)
N0++;
if (document.getElementById('Reg').value != "" && document.getElementById('DOB').value != "")
N1 = 2;
else
N1 = 0;
if (N0 == 3 && N1 == 2)
document.getElementById('submit').removeAttribute('disabled')
else
if (document.getElementById('submit').hasAttribute('disabled') == true)
else
document.getElementById('submit').disabled = true
【问题讨论】:
【参考方案1】:您需要删除<form>
和</form>
标签,如下所示:
<div class="col-md-6">
<div class="h-100 p-5 bg-light border rounded-3">
<h2>Non-Changable Details</h2>
<form> <!-- Remove this tag -->
...
</form> <!-- Remove this tag -->
</div>
</div>
由于@Html.BeginForm()
将生成<form>
元素,<form>
元素将与提到的<form>
元素一起崩溃,因此 POST 方法没有触发。
同时,建议您阅读article,了解 C# 中的命名约定最佳实践。
【讨论】:
非常感谢,我为这些挠头 2 天..也感谢您的那篇文章,我在同一件事上还有一个问题,它显示我的模型状态无效我该如何解决?ModelState.IsValid
为假,因为属性值已验证但失败。您可以检查ModelState.Errors
以查看验证错误。你可以参考这个question。以上是关于提交按钮未在 ASP.NET MVC Web 应用程序中触发的主要内容,如果未能解决你的问题,请参考以下文章
jQuery Validate:在 ASP.NET MVC 5 应用程序中添加事件以提交按钮单击