如何使用 ASP.NET Core MVC 正确实现 C# 类?

问题描述 投票:0回答:1

作业是创建一个 ASP.NET Core MVC Web 应用程序,该应用程序具有

Student
StudentWorker
类。然后,您让用户输入
StudentWorker
对象的信息(ID、姓名、时薪和工作时间)。您将周薪 (hourlyPay * hoursWorked) 输出到视图,确保时薪在 (7.25 - 14.75) 范围内,工作时间在 (1 - 15) 范围内。

我毫无问题地创建了

Student
StudentWorker
类以及视图(大部分)。我很确定大多数问题都出在控制器上。 ASP.NET Core MVC 框架对我来说很难理解,我只是想完成这个 C# 类。

我将在下面列出项目文件:

模型类:

namespace FinalProject.Models
{
    public class Student
    {
        // Private fields
        private int id;
        private string name;

        // Public property for ID
        public int ID
        {
            get { return id; }
            set { id = value; }
        }

        // Public property for Name
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        // Constructors
        public Student(int id, string name)
        {
            this.id = id;
            this.name = name;
        }

        // Default constructor (demonstrates method overloading)
        public Student()
        {
            id = 0;
            name = "";
        }

        // Method to display student information (overrides default ToString method)
        public override string ToString()
        {
            return ($"ID: {ID}, Name: {Name}");
        }
    }

    public class StudentWorker : Student
    {
        // Private fields
        private double hourlyPay;
        private int hoursWorked;

        // Public property for HourlyPay
        public double HourlyPay
        {
            get { return hourlyPay; }
            set
            {
                if (value >= 7.25 && value <= 14.75)
                    hourlyPay = value;
                else
                    hourlyPay = 0;
            }
        }

        // Public property for HoursWorked
        public int HoursWorked
        {
            get { return hoursWorked; }
            set
            {
                if (value >= 1 && value <= 15)
                    hoursWorked = value;
                else
                    hoursWorked = 0;
            }
        }

        // Constructor
        public StudentWorker(int id, string name, double hourlyPay, int hoursWorked)
                    : base(id, name)
        {
            HourlyPay = hourlyPay;
            HoursWorked = hoursWorked;
        }

        // Default constructor (demonstrates method overloading)
        public StudentWorker() : base()
        {
            HourlyPay = 0;
            HoursWorked = 0;
        }

        // Method to calculate weekly salary
        public double WeeklySalary()
        {
            if (HourlyPay == 0 || HoursWorked == 0)
                return 0;

            return HourlyPay * HoursWorked;
        }

        // Method to display student worker information (overrides default ToString method)
        public override string ToString()
        {
            return ($"ID: {ID}, Name: {Name}, Hourly Pay: {HourlyPay:C}, Hours Worked: {HoursWorked}, Weekly Salary: {WeeklySalary():C}");
        }
    }
}

查看

@model FinalProject.Models.StudentWorker

@{
    ViewBag.Title = "Create Student Worker";
}
<html>
<head>
    <title>Student Worker</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>

<h2>Create Student Worker</h2>

<form asp-action="Index" method="post">
    <div class="form-group">
        <label asp-for="ID" class="control-label">Student ID</label>
        <input asp-for="ID" class="form-control" />
        <span asp-validation-for="ID" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Name" class="control-label">Student Name</label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="HourlyPay" class="control-label">Hourly Pay</label>
        <input asp-for="HourlyPay" class="form-control" />
        <span asp-validation-for="HourlyPay" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="HoursWorked" class="control-label">Hours Worked</label>
        <input asp-for="HoursWorked" class="form-control" />
        <span asp-validation-for="HoursWorked" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">Calculate Weekly Salary</button>
</form>


@if (ViewBag.WeeklySalary != null)
{
    <h3>Weekly Salary: @ViewBag.WeeklySalary</h3>
}

</body>
</html>

控制器

using FinalProject.Models;
using Microsoft.AspNetCore.Mvc;

namespace FinalProject.Controllers
{
    public class HomeController : Controller
    {
        // GET: StudentWorker/Create
        public IActionResult Index()
        {
            return View();
        }

        // POST: StudentWorker/Create
        [HttpPost]
        public IActionResult Index(StudentWorker model)
        {
            if (ModelState.IsValid)
            {
                // Calculate weekly salary
                var weeklySalary = model.WeeklySalary();
                ViewBag.WeeklySalary = weeklySalary;

                // Return view with the weekly salary
                return View(model);
            }

            // If model state is not valid, redisplay the form
            return View(model);
        }
    }
}

我尝试删除

hourlyPay
hoursWorked
的范围,但这似乎没有任何作用。再说一次,我不熟悉编写网络应用程序,我将非常感谢任何帮助:)

c# asp.net-core-mvc .net-8.0 model-validation
1个回答
0
投票

我很确定大多数问题都出在控制器上。 MVC ASP.NET框架对我来说很难理解,我只是想了解一下 完成这门 C# 课程。

基于您共享的代码,在.NET或asp.net core甚至C#中,我们使用干净的getter和setter属性编写classes,而不是像您那样。因此,您没有得到您正在寻找的预期输出。

为了实现您的要求,您应该有

Student
StudentWorker
以及模型验证注释,如 RangeRequired 来验证您的工作时间费率和工作时间。

除此之外,您还可以在该类中编写计算付款方法。最后,如果验证通过,则将计算出的值返回给视图。

让我们看看实践中如何以更干净的方式实现它。

型号:

public class Student
{
    [Required]
    public int ID { get; set; }

    [Required]
    [StringLength(100)]
    public string Name { get; set; }
}

public class StudentWorker : Student
{
    [Required]
    [Range(7.25, 14.75, ErrorMessage = "Hourly pay must be between $7.25 and $14.75")]
    public double HourlyPay { get; set; }

    [Required]
    [Range(1, 15, ErrorMessage = "Hours worked must be between 1 and 15")]
    public int HoursWorked { get; set; }

    public double WeeklySalary()
    {
        return HourlyPay * HoursWorked;
    }
}

控制器:

public class StudentWorkerController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {
        return View(new StudentWorker());
    }

    [HttpPost]
    public IActionResult CalculatePayment(StudentWorker model)
    {
        if (ModelState.IsValid)
        {
            ViewBag.WeeklySalary = model.WeeklySalary();
        }
        return View("Index");
    }
}

查看:

@model StudentWorker

@{
    ViewBag.Title = "Create Student Worker";
}
<div class="container">
    <h2>Create Student Worker</h2>

    <form asp-action="CalculatePayment" method="post">
        <div class="form-group">
            <label asp-for="ID" class="control-label">Student ID</label>
            <input asp-for="ID" class="form-control" />
            <span asp-validation-for="ID" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Name" class="control-label">Student Name</label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="HourlyPay" class="control-label">Hourly Pay</label>
            <input asp-for="HourlyPay" class="form-control" />
            <span asp-validation-for="HourlyPay" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="HoursWorked" class="control-label">Hours Worked</label>
            <input asp-for="HoursWorked" class="form-control" />
            <span asp-validation-for="HoursWorked" class="text-danger"></span>
        </div>
        <button type="submit" class="btn btn-primary">Calculate Weekly Salary</button>
    </form>

    @if (ViewBag.WeeklySalary != null)
    {
        <h3>Weekly Salary: $ @ViewBag.WeeklySalary</h3>
    }
</div>

输出:

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

注意: 上面的示例表示asp.net core 中的一种方法。然而,还有其他一些方法。如果您想了解,请参考此官方文档进行模型验证。和额外样本

© www.soinside.com 2019 - 2024. All rights reserved.