2012-07-28 4 views
0

이 내 모델이 컨트롤러는MVC3에서 유효성 검사가 작동하지 않습니까?

  #region Insert New Project 
    // 
    //View for adding new Projects/ 
    // 
    [AcceptVerbs(HttpVerbs.Get)] 
    public ActionResult Create() 
    { 
     ViewBag.Status = new SelectList(GetStatus(), "Status", "Status"); 
     return View(); 
    } 

    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Create(ProjectModel model,string Status) 
    { 
     // var modelList = new List<ProjectModel>(); 
     using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True")) 
     { 
      conn.Open(); 
      SqlCommand insertcommande = new SqlCommand("Sp_AddNewProject", conn); 
      insertcommande.CommandType = CommandType.StoredProcedure; 
      insertcommande.Parameters.Add("@ProjectName", SqlDbType.VarChar).Value = model.projectName; 
      insertcommande.Parameters.Add("@Description", SqlDbType.VarChar).Value = model.Description; 
      insertcommande.Parameters.Add("@Status", SqlDbType.VarChar).Value =Status; 
      insertcommande.ExecuteNonQuery(); 
     } 
     return RedirectToAction("Create"); 
    } 


     #region To Edit th Existing Project Record 
    // 
    //View For displaying the record to be edited/ 
    // 
    [AcceptVerbs(HttpVerbs.Get)] 
    public ActionResult Edit(int id, ProjectModel updatemodel) 
    { 
     ViewBag.Status = new SelectList(GetStatus(), "Status", "Status"); 
     SqlConnection cn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"); 
     SqlCommand cmd = new SqlCommand("Select ProjectId,projectName,Description,status From Projects Where ProjectId=" + id, cn); 
     cn.Open(); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     if (dr.Read()) 
     { 
      //if (dr[0]) != DBNull.Value) 
      updatemodel.ID = Convert.ToInt16(dr["ProjectId"]); 
      updatemodel.projectName = dr["projectName"].ToString(); 
      updatemodel.Description = dr["Description"].ToString(); 
      updatemodel.status = dr["status"].ToString(); 
     } 
     else 
     { 
      dr.Close(); 
     } 
     dr.Close(); 
     cn.Close(); 
     return View(updatemodel); 
    } 
    // 
    //Action for editing the record which is in view/ 
    // 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Edit(ProjectModel updatemodel, FormCollection form, int id,string Status) 
    { 

     SqlConnection cn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"); 
     SqlCommand cmd = new SqlCommand("UpdateProject", cn); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cn.Open(); 
     cmd.Parameters.Add("ProjectId", SqlDbType.Int).Value = updatemodel.ID; 
     cmd.Parameters.Add("projectName", SqlDbType.VarChar).Value = updatemodel.projectName; 
     cmd.Parameters.Add("Description", SqlDbType.VarChar).Value = updatemodel.Description; 
     cmd.Parameters.Add("status", SqlDbType.VarChar).Value = Status; 
     cn.Close(); 
     return View(updatemodel); 
    } 

    #endregion 

모습입니다

 public class ProjectModel 
     { 
     public static List<ProjectModel> GetList { get; set; } 
     public Int16 ID { get; set; } 
     [Required(ErrorMessage = "ProjectName is required")] 
     public string projectName { get; set; } 
     [Required(ErrorMessage = "Description is required")] 
     public string Description { get; set; } 
     [Required(ErrorMessage = "Status is required")] 
     public string status { get; set; } 
     } 

모습이 내 aspx 페이지 내 문제가되는 검증이에서 해고되지 않습니다이다

 <% using (Html.BeginForm()) 
    { %> 
    <%-- <form action="Create.aspx" method="post"></form>--%> 
    <%:Html.ValidationSummary(true)%> 
    <fieldset> 
    <legend style="color:Orange; font-weight:bolder;">AddNew Project</legend> 

    <div class="editor-label" style="color:Orange; font-weight:bolder;"> 
     <%: Html.LabelFor(model => model.projectName)%> 
    </div> 
    <div class="editor-field"> 
     <%:Html.EditorFor(model => model.projectName)%> 
     <%: Html.ValidationMessageFor(model => model.projectName)%> 
    </div> 

    <div class="editor-label" style="color:Orange; font-weight:bolder;"> 
     <%:Html.LabelFor(model => model.Description)%> 
    </div> 
    <div class="editor-field"> 
     <%:Html.EditorFor(model => model.Description)%> 
     <%:Html.ValidationMessageFor(model => model.Description)%> 
    </div> 
    <div class="editor-label" style="color:Orange; font-weight:bolder;"> 
    <%:Html.LabelFor(model => model.status)%> 
    </div> 
    <div class="editor-field"> 
    <%:Html.DropDownList("Status")%> 
    <%:Html.ValidationMessageFor(model => model.status)%> 
    </div> 
    <p> 
     <input type="submit" value="Create" style="color:Orange; font-weight:bolder;"/> 
     </p> 
    </fieldset> 
<%} %> 

모습입니다 어떻게 내 새 페이지 작성 버튼을 클릭하면 제출 버튼 하지만 유효성 검사를하기 전에 심지어 내 편집 페이지에서 cilck get 수 있습니다 하나 whe 다시 내가 잘못

을하고 또는 당신은 실제로 검증이 실패 있는지 확인되지 검증

+0

의견이 맞지 않습니다. 유효성 검사가 실행되지 않는다고 말하면 페이지가로드되기 전에 유효성 검사가 진행 중입니까? 질문을 명확하게하십시오. –

+0

@MystereMan 유효성 검사는 작성 페이지에서 실행되지 않지만 편집 페이지에서 유효성 검사는 내 페이지로드에서 발생합니다. – SoftwareNerd

+0

이 질문에 추가 한 뷰의 이름은 무엇입니까? – Yasser

답변

0

를 제공하기 위해 다른 방법이입니다. 당신이 게시 컨트롤러 방법, 당신은 확인이 필요합니다 :

if (ModelState.IsValid) { 
    // do your work 

    return RedirectToAction("WhereYouWantToGoAfterwards"); 
} 

return View(model); 

편집 :

제가 위에서 말했듯이, 당신이 실제로 코드에서 오류를 검사 아닙니다. 그러나 Create와 Edit 사이에 다른 효과가 나타나는 것은 편집에서 View()를 반환하지만 Create your RedirectToAction에있는 것입니다. Redirect가 ModelState를 지우므로 오류가 표시되지 않습니다.

데이터를 기반으로 작업을 시작하기 전에 ModelState.IsValid가 여전히 확인해야합니다. 그렇지 않으면 많은 어려움을 겪을 것입니다.

관련 문제