작은 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();
}
잘못 입력하지만 난 잘못을 이해하지 않으면 내가 뷰 자체에 메시지가했는데
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>
내 create
볼 수 있습니다.
? 그런 다음 클래스 객체를 생성하고 추가합니다. 그게 뭐가 잘못 됐나? – pluto20010
각 매개 변수를 직접 확인하십시오. if (Name == null) {ModelState.AddModelError ("Name is required")} ...'그런 다음'ModlState.IsValid'를 호출하십시오. –