I am new to ASP.NET and C#, by looking some tutorial I tried to make a site for voting but the submit button is not working at all, have tried all the solutions given here but still, now it is not working.
Home Controller:
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 protected]", "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 SmtpClient{Host = "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 page:
@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" width="40" height="40">
<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 = "[email protected]", @Value = "name", @disabled = "disabled" } })
@Html.ValidationMessageFor(model => model.Email_Id, "", new { @class = "text-danger" })
@*<input type="text" class="form-control" id="floatingInputValue" placeholder="[email protected]" value="[email protected]" 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 = "[email protected]", @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>
For Data validation, I have used this in another folder called extended and erased the folder name from the namespace
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;
}
}
}
Actual class generated by 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 file used for adding some action:
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
}
}
}
CodePudding user response:
You need to remove the <form>
and </form>
tags as below:
<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>
As @Html.BeginForm()
will generate <form>
element which the <form>
element will crash with the <form>
element mentioned and hence the POST method was not firing.
Meanwhile, will recommend you to read this article for naming convention best practices in C#.