【问题标题】:MVC C# Input Button does not return to controllerMVC C# 输入按钮不返回到控制器
【发布时间】:2021-04-16 22:21:04
【问题描述】:

我正在尝试构建一个系统,当用户可以登录时,会看到一个选项菜单,从菜单中选择一个,然后根据该选择转到另一个屏幕。

我以这个网站为起点: https://www.mindstick.com/blog/647/creating-a-simple-data-entry-application-using-asp-dot-net-mvc-4

但是,当我尝试使用输入按钮创建第二个屏幕时,系统永远不会返回到控制器,而是返回到登录屏幕。不知何故,在不执行任何控制器代码的情况下,它会显示“无效的用户名/密码”消息。

控制器:

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

    }
}

INDEX.cshtml 视图:

@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>

“PickLocation”屏幕——如果用户被授权申请多个帐户,代码会转到此屏幕:

@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>

ShowLocation.cshtml 屏幕:

@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>

什么会导致系统无法正确处理 PickLocation 屏幕或 ShowLocation 屏幕上的提交按钮?

另外,我想知道我是否应该使用“表单身份验证”来执行此操作。你能指出我正确的方向吗?

【问题讨论】:

    标签: c# html asp.net-mvc


    【解决方案1】:

    指定您的请求应参考哪个控制器和方法

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

    【讨论】:

    • 谢谢你——正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2020-11-17
    相关资源
    最近更新 更多