2017-12-28 16 views
-1

작은 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 볼 수 있습니다.

답변

1

여러 개의 문자열을 전달하는 대신 모델을 생성 작업에 전달해야합니다. student1 클래스를 Create 조치에 전달한 후 ModelState.IsValid을 호출하여 모델이 유효한지 확인하십시오.

public ActionResult Create(student1 student) 
{ 
    if(ModelState.IsValid) 
    { 
     studentDemoEntities.student1.Add(student); 
     studentDemoEntities.SaveChanges() 

     return RedirectToAction("Index"); 
    } 

    return View(student); 
} 

당신이 SaveChanges를 호출 할 때 당신은 또한 유효하지 않은 속성을 확인할 수 있습니다

내가 문자열을 전달하면 무슨 일이 벌어지고
if(ModelState.IsValid) 
{ 
    studentDemoEntities.student1.Add(stud); 
    try 
    { 
     return studentDemoEntities.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    catch (DbEntityValidationException dbEx) 
    { 
     foreach (var validationErrors in dbEx.EntityValidationErrors) 
     { 
      foreach (var validationError in validationErrors.ValidationErrors) 
      { 
       Debug.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); 
      } 
     } 
     return Index(student); 
    } 
} 
+0

? 그런 다음 클래스 객체를 생성하고 추가합니다. 그게 뭐가 잘못 됐나? – pluto20010

+1

각 매개 변수를 직접 확인하십시오. if (Name == null) {ModelState.AddModelError ("Name is required")} ...'그런 다음'ModlState.IsValid'를 호출하십시오. –

관련 문제