English 中文(简体)
如何运用ASP.
原标题:How to I properly implement C# classes using ASP.NET Core MVC?
The assignment is to create an ASP.NET Core MVC web app that has a Student and a StudentWorker class. You then have the user input the information for a StudentWorker object (id, name, hourly pay, and hours worked). You output the weekly salary (hourlyPay * hoursWorked) to the view, making sure that the hourly pay is in the range (7.25 - 14.75), and the hours worked is in the range (1 - 15). I created both the Student and StudentWorker classes with no problems, as well as the view (for the most part). I m pretty sure most of the issues lie in the controller. The ASP.NET Core MVC framework is hard for me to understand, and I m just trying to complete this C# class. I ll list the project files below: Model classes: 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}"); } } } View @model FinalProject.Models.StudentWorker @{ ViewBag.Title = "Create Student Worker"; } Student Worker

Create Student Worker

@if (ViewBag.WeeklySalary != null) {

Weekly Salary: @ViewBag.WeeklySalary

} Controller 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); } } } I ve tried removing the ranges for hourlyPay and hoursWorked, but that doesn t seem to do anything. Again, I m unfamiliar with writing web apps, and I would greatly appreciate any help :)
最佳回答
I m pretty sure most of the issues lie in the Controller. The MVC ASP.NET framework is hard for me to understand, and I m just trying to complete this C# class. Based on your shared code, in .NET or asp.net core or even in C# we write classes with clean getter and setter attribute, not the way you did. Therefore, you are not getting the expected output you are looking for. In order to implement your requirement, you should have Student and StudentWorker with the model validation annotation like Range, Required to validate your working hours rate and working hours. In addition to this, you could write the calculate payment method inside that class as well. Finally, return the claculated value to the view if the validation passed. Let s have a look in practice, how we can implement that in cleaner way. Model: 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; } } Controller: 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"); } } View: @model StudentWorker @{ ViewBag.Title = "Create Student Worker"; }

Create Student Worker

@if (ViewBag.WeeklySalary != null) {

Weekly Salary: $ @ViewBag.WeeklySalary

}
Upate: Project structure: Be informed that, Middleware, Enum, services is my custom folder. Controller: Model: View: Program.cs files is default when the project created. And the routing is also default like below: var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); Output: Note: Above sample denotes one of the apporach in asp.net core. However, there are couple of other way as well. If you want to know, please refer to this offcial document for Model validation. and additional sample.
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签