简体   繁体   中英

MVC C# Input Button does not return to controller

I am trying to build a system when a user can log in, be presented with a menu of options, select one from the menu and then go to another screen based on that selection.

I used this web site as a starting point: https://www.mindstick.com/blog/647/creating-a-simple-data-entry-application-using-asp-dot-net-mvc-4

However, when I try to create a second screen with an input button, the system never returns to the controller and instead goes back to the login screen. Somehow, without executing any controller code it puts up the "invalid username/password" message.

The Controller:

using gcbTaxFormEntry.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;

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

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

        //
        // GET: /Home/
        public IActionResult Index()
        { 
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

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

        [HttpGet]
        public ViewResult Staff() { return View(); }
        [HttpGet]
        public ViewResult PickLocation() { return View(); }
        

        [HttpPost]
        public ViewResult Index(AuthInfo AI)
        {
            if (AI.Uname == null || AI.Pword == null)
            {
                ModelState.AddModelError("LogOnError", "Invalid Username/Password");
                return View("Index");
            }

            AI.Uname = AI.Uname.ToLower();

            MySqlConnection myConnection = new();
            MySqlCommand myCommand = new();
            MySqlDataAdapter myAdapter = new();

            string ErrorMessage = SQLdbOpen(myConnection, myCommand);
            if (ErrorMessage != string.Empty)
            {
                ModelState.AddModelError("LogOnError", ErrorMessage);
                return View("Index");
            }

            DataTable AuthInfo = new();
            string PassHash = ComputeSha256Hash(AI.Uname + AI.Pword);
            myCommand.CommandText = "SELECT * FROM gcb.auth WHERE " +
                                    "uname = ?uname AND passhash = ?passhash";
            myCommand.Parameters.AddWithValue("?uname", AI.Uname);
            myCommand.Parameters.AddWithValue("?passhash", PassHash);
            myAdapter.SelectCommand = myCommand;
            myAdapter.Fill(AuthInfo);
            myCommand.Parameters.Clear();

            if (AuthInfo.Rows.Count != 1)
            {
                ModelState.AddModelError("LogOnError", "Invalid Username/Password");
                return View("Index");
            }

            CommonInfo Common = new();
            Common.Uname = AI.Uname;
            Common.Firstname = Convert.ToString(AuthInfo.Rows[0]["Firstname"]);
            Common.Lastname = Convert.ToString(AuthInfo.Rows[0]["Lastname"]);

            DataTable AuthLocationInfo = new();
            myCommand.CommandText = "SELECT * FROM gcb.authlocations " +
                "join gcb.locationinfo on authlocations.locationnumber = locationinfo.locationnumber " +
                "WHERE uname = ?uname";
            myCommand.Parameters.AddWithValue("?uname", Common.Uname);
            myAdapter.SelectCommand = myCommand;
            myAdapter.Fill(AuthLocationInfo);
            myCommand.Parameters.Clear();
            myConnection.Close();

            switch (AuthLocationInfo.Rows.Count)
            {
                case 0:
                    ModelState.AddModelError("LogOnError", "No Authorized Locations");
                    return View("Index");

                case 1:
                    Common.LocationNumber = Convert.ToString(AuthLocationInfo.Rows[0]["LocationNumber"]);
                    Common.PrimaryName = Convert.ToString(AuthLocationInfo.Rows[0]["PrimaryName"]);
                    Common.Address = Convert.ToString(AuthLocationInfo.Rows[0]["Address"]);
                    Common.City = Convert.ToString(AuthLocationInfo.Rows[0]["City"]);
                    Common.County = Convert.ToString(AuthLocationInfo.Rows[0]["County"]);
                    Common.Area = Convert.ToString(AuthLocationInfo.Rows[0]["Area"]);
                    return View("ShowLocation", Common);

                default:
                    return View("PickLocation", Common);
            }
        }

        [HttpPost]
        public ViewResult ShowLocation(CommonInfo Common)
        {
            string NextForm = Common.SelectedForm + "Form";
            return View(NextForm, Common);
        }

        [HttpPost]
        public ViewResult PickLocation(CommonInfo Common)
        {
            if (Common.LocationNumber == null)
            {
                ModelState.AddModelError("PickLocationMessage", "Invalid");
                return View("PickLocation");
            }

            MySqlConnection myConnection = new();
            MySqlCommand myCommand = new();
            MySqlDataAdapter myAdapter = new();

            string ErrorMessage = SQLdbOpen(myConnection, myCommand);
            if (ErrorMessage != string.Empty)
            {
                ModelState.AddModelError("PickLocationMessage", ErrorMessage);
                return View("PickLocation");
            }

            myCommand.Parameters.Clear();

            DataTable LocationInfo = new();
            myCommand.CommandText = "SELECT * FROM gcb.locationinfo WHERE " +
                                    "LocationNumber = ? LocationNumber";
            myCommand.Parameters.AddWithValue("?LocationNumber", Common.LocationNumber);
            myAdapter.SelectCommand = myCommand;
            myAdapter.Fill(LocationInfo);

            if (LocationInfo.Rows.Count != 1)
            {
                myCommand.Parameters.Clear();
                myConnection.Close();
                ModelState.AddModelError("PickLocationMessage", "Invalid");
                return View("PickLocation");
            }

            DataTable AuthLocations = new();
            myCommand.CommandText = "SELECT * FROM gcb.authlocations WHERE " +
                                    "uname = ?uname AND LocationNumber = ?LocationNumber";
            myCommand.Parameters.AddWithValue("?uname", Common.Uname);
            myAdapter.SelectCommand = myCommand;
            myAdapter.Fill(AuthLocations);
            myCommand.Parameters.Clear();
            myConnection.Close();

            if (AuthLocations.Rows.Count != 1)
            {
                myCommand.Parameters.Clear();
                myConnection.Close();
                ModelState.AddModelError("PickLocationMessage", "Not Authorized");
                return View("PickLocation");
            }

            Common.PrimaryName = Convert.ToString(LocationInfo.Rows[0]["PrimaryName"]);
            Common.Address = Convert.ToString(LocationInfo.Rows[0]["Address"]);
            Common.City = Convert.ToString(LocationInfo.Rows[0]["City"]);
            Common.County = Convert.ToString(LocationInfo.Rows[0]["County"]);
            Common.Area = Convert.ToString(LocationInfo.Rows[0]["Area"]);

            return View("ShowLocation", Common);
        }

        
        private static string ComputeSha256Hash(string rawData)
        {
            // Create a SHA256   
            using SHA256 sha256Hash = SHA256.Create();
            // ComputeHash - returns byte array  
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));

            // Convert byte array to a string   
            StringBuilder builder = new();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }

        public string SQLdbOpen(MySqlConnection myConnection, MySqlCommand myCommand)
        {
            string ConnectionString = string.Empty;
            string CSfilename = @"C:\users\mark\documents\mysql\ConnectionString.txt";

            try
            {
                StreamReader cs = new(CSfilename);
                while (!cs.EndOfStream)
                {
                    ConnectionString += cs.ReadLine() + "; ";
                }
                cs.Close();
                myConnection.ConnectionString = ConnectionString;
                myConnection.Open();
                myCommand.Connection = myConnection;
            }
            catch (MySqlException E)
            {
                return E.Message;
            }

            return string.Empty;
        }

    }
}

The INDEX.cshtml view:

@model gcbTaxFormEntry.Models.AuthInfo
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <link href="~/css/site.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width" />
    <title>Login</title>
</head>

<body>
    <h3 style="text-align: center"><img src=@Url.Content("/Images/Badge.jpg") width=200 height=200 /></h3>
    <h1 style="text-align: center">Island of Montague</h1>
    <h2 style="text-align: center">Gaming Control Board</h2>
    <h3 style="text-align: center">Tax Form Entry System</h3>
    <br />
    @using (Html.BeginForm())
    {
        <table align="center">
            <tr>
                <td>Username :</td>
                <td>@Html.TextBoxFor(m => m.Uname)</td>
            </tr>
            <tr>
                <td>Password :</td>
                <td>@Html.PasswordFor(m => m.Pword)</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@Html.ValidationMessage("LogOnError")</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Login" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@Html.ActionLink("Meet Our Staff", "Staff")</td>
            </tr>
        </table>
    }
</body>
</html>

The "PickLocation" screen -- code goes to this if the user is authorized to file for more than one account:

@model gcbTaxFormEntry.Models.CommonInfo
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <link href="~/css/site.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width" />
    <title>Pick Location</title>
</head>
<body>
    <h1 style="text-align: center">
        <img src=@Url.Content("/Images/Badge.jpg") width=80 height=80 />
        Island of Montague
        <img src=@Url.Content("/Images/Badge.jpg") width=80 height=80 />
    </h1>
    <h2 style="text-align: center">Gaming Control Board</h2>
    <br />
    <p style="text-align: center">Welcome @Model.Firstname @Model.Lastname (@Model.Uname)</p>
    <br />
    @using (Html.BeginForm())
    {
        <table align="center">
            <tr>
                <td>Account Number</td>
                <td>@Html.TextBoxFor(m => m.LocationNumber)</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>@Html.ValidationMessage("PickLocationMessage")</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Select" /></td>
            </tr>
        </table>
    }
</body>
</html>

The ShowLocation.cshtml screen:

@model gcbTaxFormEntry.Models.CommonInfo
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <link href="~/css/site.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width" />
    <title>Show Location</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        <h1 style="text-align: center">
            <img src=@Url.Content("/Images/Badge.jpg") width=80 height=80 />
            Island of Montague
            <img src=@Url.Content("/Images/Badge.jpg") width=80 height=80 />
        </h1>
        <h2 style="text-align: center">Gaming Control Board</h2>

        <p style="text-align: center">Welcome @Model.Firstname @Model.Lastname (@Model.Uname)</p>
        <p style="text-align: center"><b>Selected Location</b></p>
        <table align="center" border="1">
            <tr>
                <td align="center">Account Number</td>
                <td align="center">Primary Name</td>
                <td align="center">Address</td>
                <td align="center">City</td>
            </tr>
            <tr>
                <td>@Html.TextBoxFor(m => m.LocationNumber, new { @readonly = "readonly" })</td>
                <td>@Html.TextBoxFor(m => m.PrimaryName, new { @readonly = "readonly" })</td>
                <td>@Html.TextBoxFor(m => m.Address, new { @readonly = "readonly" })</td>
                <td>@Html.TextBoxFor(m => m.City, new { @readonly = "readonly" })</td>
            </tr>
        </table>
        <br />
        <table align="center">
            <tr>
                <td align="center"><b>Create A Draft Tax Form</b></td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td align="center"><b>Review and File a Draft Tax Form</b></td>
            </tr>
            <tr>
                <td align="center">
                    @Html.DropDownListFor(m => m.SelectedForm, new[]{
            new SelectListItem() { Text = "NGC-01  Monthly Gross Revenue Report", Value = "NGC01" },
            new SelectListItem() { Text = "NGC-02  Annual Fee for Games", Value = "NGC02" },
            new SelectListItem() { Text = "NGC-04  Annual Fee for Slots", Value = "NGC04" },
            new SelectListItem() { Text = "NGC-11  Live Entertainment Tax Report", Value = "NGC11" },
            new SelectListItem() { Text = "NGC-12  Live Entertainment Tax Report", Value = "NGC12" },
            new SelectListItem() { Text = "NGC-14  Quarterly State License Fee (Restricted)", Value = "NGC14" },
            new SelectListItem() { Text = "NGC-15  Quarterly State License Fee (Non-Restricted)", Value = "NGC15" },
            new SelectListItem() { Text = "NGC-16  Holiday or Special Event Application", Value = "NGC16" },
            new SelectListItem() { Text = "NGC-17  Standard Financial Statement", Value = "NGC17" },
            new SelectListItem() { Text = "NGC-17A Standard Financial Statement for SRO", Value = "NGC17A" },
            new SelectListItem() { Text = "NGC-18  Report of Quarterly Expired Slot Machine Wagering Vouchers", Value = "NGC18" },
            new SelectListItem() { Text = "NGC-19M Manufacturer of Interactive Gaming Systems License", Value = "NGC19M" },
            new SelectListItem() { Text = "NGC-19O Operator of Interactive Gaming License", Value = "NGC19O" },
            new SelectListItem() { Text = "NGC-19P Interactive Gaming Service Provider License", Value = "NGC19P" },
            new SelectListItem() { Text = "NGC-20  Racing Information Disseminators Monthly Report (Info)", Value = "NGC20" },
            new SelectListItem() { Text = "NGC-20A Racing Information Disseminators Monthly Report", Value = "NGC20A" },
            new SelectListItem() { Text = "NGC-21D Distributor's License", Value = "NGC21D" },
            new SelectListItem() { Text = "NGC-21M Manufacturer's License", Value = "NGC21M" },
            new SelectListItem() { Text = "NGC-21P Operator of a Pari-Mutuel System License", Value = "NGC21P" },
            new SelectListItem() { Text = "NGC-25  Operator of a Slot Machine Route License", Value = "NGC25" },
            new SelectListItem() { Text = "NGC-25I Operator of a Inter-Casino Linked System License", Value = "NGC25I" },
            new SelectListItem() { Text = "NGC-25O Operator of a Mobile Gaming System License", Value = "NGC25O" },
            new SelectListItem() { Text = "NGC-27  Opeartor of an Information Service License", Value = "NGC27" },
            new SelectListItem() { Text = "NGC-30  Monthly Gross Revenue Statistical Report Gaming Salon", Value = "NGC30" },
            new SelectListItem() { Text = "NGC-31  Monthly Gross Revenue Statistical Report", Value = "NGC31" },
            new SelectListItem() { Text = "NGC-32  Track Handle and Win Report", Value = "NGC32" },
            new SelectListItem() { Text = "NGC-36  Slot Route Operator Informational Report", Value = "NGC36" },
            new SelectListItem() { Text = "NGC-PMT-1 Pari-Mutuel Wagering Tax", Value = "NGCPMT1" },
            new SelectListItem() { Text = "ER101   Monthly Condensed Financial Statements", Value = "ER101" },
                      }, "Choose a Tax Form")
                            </td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td align="center">Imagine a Dropdown box here</td>
            </tr>
        </table>
        <table align="center">
            <tr>
                <td>@Html.ValidationMessage("ShowLocationMessage")</td>
            </tr>
            <tr>
                <td><input type="submit" value="Go" /></td>
            </tr>
        </table>
    }
</body>
</html>

What would be causing the system not to properly handle the submit button on either the PickLocation screen or the ShowLocation screen?

Also, I am wondering if I should be doing this using "Form Authentication". Can you point me in the right direction for an example of that?

Specify to which controller and method your request should be referred

@using (Html.BeginForm("PickLocation", "Home",FormMethod.Post))
{
   ...
}

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