2012-06-25 2 views
1

이 내 asp.net의 MVC의 내 모델이 프로젝트입니다 :는 Html.ValidationMessageFor의 asp.net MVC에서 doen't 작업은 2

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel; 
using System.ComponentModel.DataAnnotations; 
using System.Web.DynamicData; 
using System.Web.Security; 
using System.Globalization; 
using System.Web.Profile; 

namespace EMS.Models 
{ 
public class UserModels 
{ 

    [Required(ErrorMessage = "*")] 
    public string userName { get; set; } 

    [Required(ErrorMessage = "*")] 
    public string passWord { get; set; } 
    } 
} 

그리고 이것은 내보기입니다 :

<% Html.EnableClientValidation(); %> 
    <% using (Html.BeginForm()) { %> 

    <table> 
      <tr> 
       <td><label for="userlogin">User Login:</label></td> 
       <td> 
        <%: Html.TextBoxFor(m => m.userName, new { id = "userName"})%> 
        <%: Html.ValidationMessageFor(m => m.name)%> 
       </td> 
       <td><label for="password">Password:</label></td> 
       <td> 
        <%: Html.PasswordFor(m => m.passWord, new { id = "password"})%> 
        <%: Html.ValidationMessageFor(m => m.passWord)%> 
       </td> 
      </tr> 
      <tr> 
       <td colspan="4"> 
        &nbsp; <input type="submit" name="enter_infor" id="enter_infor" value="Enter Information"/> 
       </td> 
      </tr> 
    </table> 

그리고 이것은 내 컨트롤러입니다 :

[HttpPost] 
    public ActionResult UserMaintenance(FormCollection frm) 
    { 
     UserModels candidate = new UserModels 
     { 
      userName = frm["userName"].ToString(), 
      passWord = frm["passWord"].ToString() 
     }; 

     DBSEntities context = new DBSEntities(); 
     UserName user = new UserName(); 
     context.AddToUserNames(user); 
     context.SaveChanges(); 
     return View(); 
    } 

문제점 : 사용자가 사용자 이름과 암호 텍스트 상자를 모두 입력했는지 여부에 관계없이 유효성을 검사하고 싶습니다. 그러나 위의 모든 코드는 사용자가 유효성 검사 메시지없이 제출할 수 있습니다. Site.Master 준비에 스크립트를 포함 시켰습니다. 누구나 말해 줄 수 있어요, 내가 잘못 했어?

감사합니다.

답변

2

한 가지 사실은 POST 중에 모델 상태를 확인하지 않고 강력한 유형의 컨트롤러/액션 및 뷰를 사용해야한다는 것입니다. ClientValidation을 작동 시키더라도 클라이언트 측 물건이 우회되지 않았는지 확인하기 위해 서버 측 검사를 수행해야합니다. 당신은 다음에 POST 방법을 변경할 수

[HttpPost] 
     public ActionResult UserMaintenance(UserModels candidate) 
     { 
      //If the model is not valid, return the view with the posted values 
      //Validation messages will appear where appropriate based on your 
      //View Model 
      if(!modelState.isValid()){ 
       return View(candidate); 
      } 

      DBSEntities context = new DBSEntities(); 
      //Not sure what this code was doing, you were creating a variable 
      //and then never setting the properties from the FormCollection on 
      //this new variable. This seems to be the correct way below, but 
      //whatever you need to do to get this POSTed info to your DB.... 
      context.AddToUserNames(candidate); 
      context.SaveChanges(); 
      return View(); 
    } 

지금까지 당신이 적절한 스크립트와 올바른 순서 (당신이 당신의 질문에 사람들을 나열 할 수 있습니다?)

를 포함 한 ClientSideValidation 물건, 더블 체크 등
+0

답장을 보내 주셔서 감사합니다. – Nothing

2

컨트롤러 동작에 ModelState.IsValid을 사용해야합니다. 그렇지 않으면 설정 한 모든 유효성 검사가 쓸모가 없습니다.

public ActionResult UserMaintenance(UserName user) 
{ 
    if(ModelState.IsValid) // save the user only if it is valid 
    { 
     DBSEntities context = new DBSEntities(); 
     context.AddToUserNames(user); 
     context.SaveChanges(); 
     return RedirectToAction("Index") // redirect to some other action or whatevery you wish 
    } 

    return View(); // else return the same view this will show all the validation errors 
}