Exemple #1
0
        public async Task <IActionResult> Create([Bind("Id,Name,Age,PrefectureId")] Person person)
        {
            if (ModelState.IsValid)
            {
                _context.Add(person);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["PrefectureId"] = new SelectList(_context.Prefecture, "Id", "Name", person.PrefectureId);
            return(View(person));
        }
        public async Task <IActionResult> Create([Bind("Id,Name,Age")] Person person)
        {
            if (ModelState.IsValid)
            {
                // 2.5.2 Controller内にチェックロジックを入れてみる
                // (実務的にはControllerにドメインロジックを入れないほうが良いと思うけど)
                if (person.Age < 20)
                {
                    ModelState.AddModelError(nameof(person.Age), "二十歳未満です");
                    return(View(person));
                }
                _context.Add(person);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(person));
        }