ASP.NET Core 3 MVC学習例1

47235 ワード

1.Modelファイル、Studioクラスの追加
public class Student
{
	public int Id{get;set;}
	public string FirstName{get;set;}
	public string LastName{get;set;}
	public DateTime BirthDate{get;set;}
	public Gender Gender{get;set}
}
public enum Gender
{
	  = 0,
	  =1,
	   = 2
}

2.Servicesフォルダ汎用インタフェースIrepositoryを追加し、そのインタフェースを継承するInMemroyRepositoryクラス
public interface IRepository<T> where T:class
{
	IEnumerable<T> GetAll();
	T GetId(int Id);
	T Add(T newModel);
}
public class InMermoryRepository:IRepository<Student>
{
	private List<Student> _students;
	
	public InMermoryRepository()
	{
		-_students = new List<Student>
		{
			new Student
			{
				Id = 1,
				FirstName = "Nick",
				LastName = "Carter",
				BirthDate = new DateTime(1980,1,3)
			},
			new Student
			{
				Id = 2,
				FirstName = "Jack",
				LastName = "Harte",
				BirthDate = new DateTime(1984,1,3)
			},
			new Student
			{
				Id = 3,
				FirstName = "LiLy",
				LastName = "Lenda",
				BirthDate = new DateTime(1987,1,3)
			},
		};
	}
	public IEnumerable<Student> GetAll()
	{
		return _students;
	}
	public Student GetById(int id)
	{
		return _students.FirstorDefault(x => x.Id == id);
	}
	public Student Add(Student newModel)
	{
		int maxId = _students.Max(x => x.Id);
		newModel.Id = maxId+1;
		_students.Add(newModel);
		return newModel;
	}
}

3.Dataフォルダに、DataContextクラスを追加
public class DataContext:DbContext
{
	public DataContext(DbContextOptions<Student> options)
	    :base(options)
	{}
	public DbSet<Student> Students {get;set;}
}

4.Startupクラスおよびappsettings.jsonファイル
public class Startup
{
	private readonly IConfiguration _configuration;
	public Startup(IConfiguration configuration)
	{
		_configuration = configuration;
	}
	
	public void ConfigureServices(IServiceCollection services)
	{
		services.AddMvc();
		
		services.AddDbContext<DataContext>(options =>
		options.UseSqlServer(_configuration.GetConnectionString("DefaultConnectiong")));
		
		
		services.AddSingleton<IRepository<Student>,InMemoryRepositoy>();
	}
	
	public void Configure(IApplicationBuilder app, IWebHostEnviroment env)
	{
		if(env.IsDevelopment())
		{
			app.UseDeveloperExceptionPage();
		}
		app.UseStaticFiles();
		app.UseRouting();
		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllerRoute(
			name:"default",
			pattern:"{controller = Home}/{action = Index}/{id?}"})
	}
}
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectingStrings": {
    "DefaultConnecting": "Data Source=DESKTOP-TCEQP8C\\SQLEXPRESS;Initial Catalog=Tutorial;Integrated Security=True"

  }
}

5.ControllerフォルダにHomeControllerクラスを追加
public class HomeController:Controller
{
	private readonly IRepository<Student> _repository;
	
	public HomeController(IRepository<Student> repository)
	{
		_repository = repository;
	}
	
	public IActionResult Index()
	{
		var list = _repository.GetAll();
		
		var vms = list.Select(x => new StudentViewModel
		{
			Id = x.Id,
			Name = $"{x.FirstName}{x.LastName}",
			Age = DateTime.Now.Subtract(x.BirthDate).Days/365
		});
		
		var vm = new HomeIndexView
		{
			students = vms
		};
		return View(vm);
	}
}

Indexビュー
@using WebApplication1.Model
@model WebApplication1.ViewModels.HomeIndexViewModel
@{
   Layout = null;
}

<!DOCTYPE html>
<html>
<head>
     <meta name="viewport" content="width=device-width" />
	 <title>Hello From Index.cshtml</title>
</head>
<body>
     <h1>Students</h1>
	 <ul>
	 @foreach(var s in students)
	 {
	    <li>@s.Name @s.Age
		    <a asp-aciton = "Detail" asp-route-id = "s.Id">  Tag</a>
		</li>
	 }
	 </ul>
	 <div>
	    <a asp-aciton="Create">      </a>
	 </div>
</body>
</html>

Detail
  public IActionResult Detail(int id)
        {
            var student = _repository.GetById(id);
            if(student == null)
            {
                return RedirectToAction(nameof(Index));
            }
            return View(student);
        }

対応ビュー注意参照のmodel
@model WebApplication1.Model.Student

<!DOCTYPE html>

<html>
<head>
     <title>Detail</title>
</head>
<body>
     <div>
	     <h1>    </h1>
		 <h2>ID:@Model.Id</h2>
		 <div>
		        :@Model.FirstName @Model.LastName
		 </div>
		 <div>
		        :@Model.Gender
		 </div>
		 <div>
		           :@Model.BirthDate.ToString("yyy-MM-dd")
		 </div>
		  <div>
		       <a asp-action ="Index">   Home</a>
		  </div>
	 </div>
</body>
</html>

Createは検証する
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(StudentCreateViewModel student)
        {
            if(ModelState.IsValid)
            {
                var newStudent = new Student
                {
                    FirstName = student.FirstName,
                    LastName = student.LastName,
                    BirthDate = student.BirthDate,
                    Gender = student.Gender

                };
                var newModel = _repository.Add(newStudent);
                return RedirectToAction(nameof(Detail), new { id = newModel.Id });
            }
            else
            {
                return View();
            }

対応するビュー→フォームの発行
@using WebApplication1.Model
@using WebApplication1.ViewModles
@model StudentCreateViewModel
<h1>    </h1>

<form method="post">
   
    <div>
        <label asp-for="FirstName"></label>
        <input asp-for="FirstName" /></input>
        <span asp-validation-for="FirstName"></span>
      </div>
    <div>
        <label asp-for="LastName"></label>
        <input asp-for="LastName" /></input>
        <span asp-validation-for="LastName"></span>
     </div>
    <div>
        <label asp-for="BirthDate"></label>
        <input asp-for="BirthDate" type="date" /><input/>
        <span asp-validation-for="BirthDate"></span>
    </div>
    <div>
        <label asp-for="Gender"></label>
        <select asp-for="Gender" asp-items="Html.GetEnumSelectList()">
        </select>
        <span asp-validation-for="Gender"></span>
    </div>
    <div asp-validation-summary="All"></div>
    <button type="submit" name="save">  </button>
</form>

6.View Modelsフォルダに、3つのクラスを追加
 public class StudentViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
public class HomeIndexViewModel
    {
        public IEnumerable<StudentViewModel> students { get; set; }
    }
 public class StudentCreateViewModel
    {
        [Required, Display(Name = " ")]
        public string FirstName { get; set; }
        [Required, Display(Name = " "), MaxLength(10)]
        public string LastName { get; set; }
        [Display(Name = "    ")]
        public DateTime BirthDate { get; set; }
        [Display(Name = "  ")]
        public Gender Gender { get; set; }
    }