【解決方法】ASP .NET コア MVC アプリでの作成操作のエラー

プログラミングQA

[ad_1]

Hi,

I have an ASP.NET Core MVC app that contains two entities: Employee and Task. The relationship between these two entities is One-to-many. The information stored for an employee is the full name, email, phone number, date of birth, and monthly salary. The task consists of a title, description, assignee(the employee assigned to work on it), and a due date. When I want to create an employee, ModelState returns me an error: "Tasks is required". because of that error I can't create an employee. Here is the code:

私が試したこと:

ASP.NET
<pre>​

[HttpPost]
        public async Task<IActionResult> Create([Bind("FullName,Email,PhoneNumber,DateOfBirth,MonthlySalary")] Employee employee)
        {
            if(ModelState.IsValid)
            {
                _context.Add(employee);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(employee);
        }

[Click and drag to move]
​

public class Employee
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Enter first and last name")]
        [StringLength(30, ErrorMessage = "Maximum 30 characters")]
        [Display(Name = "Full name")]
        public string FullName { get; set; }

        [Required(ErrorMessage = "Enter your email")]
        [EmailAddress(ErrorMessage = "Invalid Email address")]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Enter a phone number")]
        [StringLength(20, ErrorMessage = "Maximum 20 characters")]
        [Display(Name = "Phone number")]
        public string PhoneNumber { get; set; }

        [Required(ErrorMessage = "Enter date of birth")]
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        [Display(Name = "Date of Birth")]
        public DateTime DateOfBirth { get; set; }

        [Required(ErrorMessage = "Enter the monthly salary")]
        [Range(30000,300000, ErrorMessage = "Salary must be in range [30000,300000]")]
        [Display(Name = "Monthly salary")]
        public int MonthlySalary { get; set; }

        public virtual ICollection<Task> Tasks { get; set; }
    }

[Click and drag to move]
​

Does anyone know what the problem is?

解決策 1

の使用ステートメントはありますか:

C#
using System.Threading.Tasks;

私はあなたのクラスをコピーし、それを切り詰めて試しました: C# オンライン コンパイラ & インタープリタ – Replit[^]

そしてそれはコンパイルされました…

C#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello, world!");
      Employee e = new Employee();
    }
}

public class Employee
{
        public int Id { get; set; }
        public virtual ICollection<Task> Tasks { get; set;}
}

[ad_2]

コメント

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