这是我创建的 ASP.NET 应用程序。 但我无法将此项目连接到我的数据库

编程

[ad_1]

我无法理解如何将其连接到数据库。 如果我想把这个项目转换成mvc该怎么做。 我是 Asp.net 的新手,并且愿意学习这一点。 请帮忙。 ASP.NET 有哪些好的前端语言,或者通常我们在一个项目中使用所有前端和后端,如下所示。 谢谢

我尝试过的:

default.aspx.cs

<pre>using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication4
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UpdateCounts();
            }
        }

        protected void btnPass_Click(object sender, EventArgs e)
        {
            InsertInspection("Pass", null);
            UpdateCounts();
        }

        protected void btnFail_Click(object sender, EventArgs e)
        {
            lblFailReason.Visible = true;
            ddlFailReason.Visible = true;
            btnFailSubmit.Enabled = false; // Disable the Submit button initially
        }

        protected void ddlFailReason_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnFailSubmit.Enabled = !string.IsNullOrEmpty(ddlFailReason.SelectedValue);
        }

        protected void btnFailSubmit_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlFailReason.SelectedValue))
            {
                InsertInspection("Fail", ddlFailReason.SelectedValue);
                UpdateCounts();
                HideFailControls();
            }
        }

        private void InsertInspection(string decision, string failReason)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand("InsertMaterialInspection", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@Decision", decision);

                    if (decision == "Pass")
                    {
                        command.Parameters.AddWithValue("@FailReason", DBNull.Value);
                    }
                    else
                    {
                        command.Parameters.AddWithValue("@FailReason", failReason);
                    }

                    command.ExecuteNonQuery();
                }
            }
        }

        private void UpdateCounts()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand("GetInspectionCounts", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            int totalCount = Convert.ToInt32(reader["TotalCount"]);
                            int passCount = Convert.ToInt32(reader["PassCount"]);
                            int failCount = Convert.ToInt32(reader["FailCount"]);

                            lblTotalCount.Text = $"Total Count: {totalCount}";
                            lblPassCount.Text = $"Pass Count: {passCount}";
                            lblFailCount.Text = $"Fail Count: {failCount}";
                        }
                    }
                }
            }
        }




        private void HideFailControls()
        {
            ddlFailReason.SelectedIndex = 0; // Reset dropdown to default
            ddlFailReason.Visible = false;
            lblFailReason.Visible = false;
            btnFailSubmit.Enabled = false; // Disable the Submit button after submitting
        }
    }
}

默认.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <div class="jumbotron">
        <h1>Material Inspection System</h1>
        <p class="lead">Inspect materials and record pass/fail decisions.</p>
    </div>

    <div class="row">
        <div class="col-md-4">
            <h2>Pass</h2>
            <asp:Button ID="btnPass" runat="server" Text="Pass" OnClick="btnPass_Click" CssClass="btn btn-success" />
        </div>
        <div class="col-md-4">
            <h2>Fail</h2>
            <asp:Button ID="btnFail" runat="server" Text="Fail" OnClick="btnFail_Click" CssClass="btn btn-danger" />
            <br />
            <asp:Label ID="lblFailReason" runat="server" Text="Reason for Failure:" Visible="false"></asp:Label>
            <asp:DropDownList ID="ddlFailReason" runat="server" Visible="false" AutoPostBack="true" OnSelectedIndexChanged="ddlFailReason_SelectedIndexChanged">
                <asp:ListItem Text="Select Reason" Value="" />
                <asp:ListItem Text="Defect" Value="Defect" />
                <asp:ListItem Text="Incorrect Specification" Value="Incorrect Specification" />
                <asp:ListItem Text="Damage" Value="Damage" />
            </asp:DropDownList>
            <br />
            <asp:Button ID="btnFailSubmit" runat="server" Text="Submit" OnClick="btnFailSubmit_Click" CssClass="btn btn-danger" Enabled="false" />
        </div>
        <div class="col-md-4">
            <h2>Inspection Summary</h2>
            <div>
                <asp:Label ID="lblTotalCount" runat="server" Text="Total Count: 0"></asp:Label><br />
                <asp:Label ID="lblPassCount" runat="server" Text="Pass Count: 0"></asp:Label><br />
                <asp:Label ID="lblFailCount" runat="server" Text="Fail Count: 0"></asp:Label>
            </div>
        </div>
    </div>

</asp:Content>

网络配置

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.1.0" newVersion="2.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

存储过程

CREATE TABLE MaterialInspections (
    InspectionID INT IDENTITY(1,1) PRIMARY KEY,
    Decision NVARCHAR(50),
    FailReason NVARCHAR(100)
);

CREATE PROCEDURE InsertMaterialInspection
    @Decision NVARCHAR(50),
    @FailReason NVARCHAR(100) = NULL
AS
BEGIN
    INSERT INTO MaterialInspections (Decision, FailReason)
    VALUES (@Decision, @FailReason);
END;

CREATE PROCEDURE GetInspectionCounts
AS
BEGIN
    SELECT
        (SELECT COUNT(*) FROM MaterialInspections) AS TotalCount,
        (SELECT COUNT(*) FROM MaterialInspections WHERE Decision = 'Pass') AS PassCount,
        (SELECT COUNT(*) FROM MaterialInspections WHERE Decision = 'Fail') AS FailCount
END

解决方案1

请参阅下面的文章来开始您的学习过程。 注释部分包含一些有价值的链接,对于初学者的理解非常有帮助。
使用 SQL Server 和实体框架设计 ASP.NET MVC 应用程序的初学者指南[^]

[ad_2]

コメント

标题和URL已复制