ASP.NET Core 3 MVC 学习例子1

1.Model文件,添加Student类

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<Gender>()">
        </select>
        <span asp-validation-for="Gender"></span>
    </div>
    <div asp-validation-summary="All"></div>
    <button type="submit" name="save">保存</button>
</form>

6.ViewModels文件夹里,添加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; }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值