Il s’agit de l’application ASP.NET que j’ai créée. Mais je n’arrive pas à connecter ce projet à ma base de données

la programmation


Je n’arrive pas à comprendre comment connecter ceci à la base de données. et si je veux convertir ce projet en mvc, comment le faire. Je suis nouveau sur Asp.net et je souhaite apprendre cela. s’il vous plaît, aidez-moi. quels sont les bons langages frontend pour asp.net ou généralement nous utilisons tous les frontend et backend dans un seul projet comme ci-dessous. Merci

Ce que j’ai essayé :

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

par défaut.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>

configuration Web

<connectionStrings>
		<add name="DefaultConnection" connectionString="Data Source=DESKTOP-RVJ62NT\SQLEXPRESS;Initial Catalog=testdb1;Integrated Security=True" providerName="System.Data.SqlClient" />
	</connectionStrings>

Procédure de magasin

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

Solution 1

Référez-vous à l’article ci-dessous pour lancer votre processus d’apprentissage. La section Note contient des liens précieux qui peuvent être très utiles pour votre compréhension en tant que débutant.
Guide du débutant pour la conception d’applications ASP.NET MVC à l’aide de SQL Server et Entity Framework[^]

コメント

タイトルとURLをコピーしました