私は小さなmvcアプリケーションを作成し、それに対する検証を実装しようとしていませんでした。このために私は私が正確なことをやっていたasp.net mvcのデータベースの最初のアプローチで検証を適用することができませんSystem.Data.Entity.Validation.DbEntityValidationException:
http://www.tutorialsteacher.com/mvc/implement-validation-in-asp.net-mvc
このチュートリアルを使用したが、エラーを取得しようとした
モデルクラス
namespace Bittu2
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class student1
{
public int StudentId { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
public string Branch { get; set; }
[Display(Name = "Mobile Number:")]
[Required(ErrorMessage = "Mobile Number is required.")]
[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Mobile Number.")]
public Nullable<int> Mobile { get; set; }
}
}
create
アクションを次のように私のコードです方法はHome Controller
private StudentDemoEntities studentDemoEntities = new StudentDemoEntities();
public ActionResult Index()
{
var s = from student1 in studentDemoEntities.student1 select student1;
return View(s);
}
[HttpPost]
public ActionResult Create(String Name, String Branch, int Mobile)
{
student1 stud = new student1();
stud.Name = Name;
stud.Branch = Branch;
stud.Mobile = Mobile;
if(ModelState.IsValid)
{
studentDemoEntities.student1.Add(stud);
studentDemoEntities.SaveChanges(); //getting exception here. System.Data.Entity.Validation.DbEntityValidationException: 'Validation failed for one or more entities.
return RedirectToAction("Index");
}
return View();
}
マイcreate
ビュー
model Bittu2.student1
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
@using (Html.BeginForm("Create", "Home"))
{
<table>
<tr>
<td>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
</td></tr>
<tr>
<td>
@Html.LabelFor(model => model.Name)
</td>
<td>
@Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.Branch)
</td>
<td>
@Html.TextBoxFor(model => model.Branch)
@Html.ValidationMessageFor(model => model.Branch, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.Mobile)
@Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
</td>
<td>
@Html.TextBoxFor(model => model.Mobile)
@Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
</td>
</tr>
</table>
<input type="submit" value="Create" />
}
<p>
</p>
@Html.ActionLink("Back to List", "Index")
</body>
</html>
は私が間違って入力されたが、私が間違っているかを理解していない場合はビュー自体にメッセージを取得することになりました。
私は、文字列を渡すと何が起こっていますか?クラスオブジェクトを作成して追加します。私は何が間違っていることを意味しますか? – pluto20010
あなたは自分で各パラメータをチェックしていますが、 'if(Name == null){ModelState.AddModelError(" Name is required ")} ...'そして 'ModlState.IsValid' –