回答編集履歴
1
追記
answer
CHANGED
@@ -9,6 +9,32 @@
|
|
9
9
|
|
10
10
|
「登録」の場面であれば、基本は上に紹介した記事の「基本 CRUD 機能を実装する」のリンク先のページの「Create ページを更新する」のセクションのコードになります。
|
11
11
|
|
12
|
+
探すのも面倒でしょうから記事のコードを以下にコピペしておきます。
|
13
|
+
|
14
|
+
```
|
15
|
+
[HttpPost]
|
16
|
+
[ValidateAntiForgeryToken]
|
17
|
+
public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student)
|
18
|
+
{
|
19
|
+
try
|
20
|
+
{
|
21
|
+
if (ModelState.IsValid)
|
22
|
+
{
|
23
|
+
db.Students.Add(student);
|
24
|
+
db.SaveChanges();
|
25
|
+
return RedirectToAction("Index");
|
26
|
+
}
|
27
|
+
}
|
28
|
+
catch (DataException /* dex */)
|
29
|
+
{
|
30
|
+
//Log the error (uncomment dex variable name and add a line here to write a log.
|
31
|
+
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
|
32
|
+
}
|
33
|
+
return View(student);
|
34
|
+
}
|
35
|
+
```
|
36
|
+
|
37
|
+
|
12
38
|
質問者さんが言う「完了」が、Create のコードで db.SaveChanges(); がエラーなく実行できたということで良ければ、次の行の return RedirectToAction("Index"); が実行されるので、一覧 (Index) が表示されることで確認できます。
|
13
39
|
|
14
40
|
質問者さんの言う「エラー」が、try 句の中で DataException (DB 関係の例外) がスローされた場合ということで良ければ、その例外が catch 句で捕捉されるので ModelState.AddModelError メソッドでエラーメッセージを設定てきます。
|