ASP.NET MVC3:创建操作的验证摘要(服务器端验证)

时间:2012-02-19 05:37:57

标签: c# asp.net-mvc asp.net-mvc-3

我在ASP.NET MVC3的模型中有一个员工类。有一个名为“EmpName”的字段。有一个用于创建员工记录的创建操作。应该有服务器端验证 - 名称的第二个字母应为“E”,名称的第三个字母应为“F”。 (没有客户端验证)。如果验证失败,则消息应作为验证摘要显示在创建视图中。我们怎么做?

注意:这两个验证的验证错误预计会产生两个错误结果(两个不同的行)。

注意:我没有使用实体框架

以下是视图代码。

@model MyApp.Employee
@{  ViewBag.Title = "Create";  }   
<h2>Create</h2>    
@using (Html.BeginForm()) 
{    
    <div >          EmpName :~: @Html.EditorFor(model => model.EmpName)  </div>      

CONTROLLER

// GET:       
public ActionResult Create()      
{                      
   return View();      
}

// POST:
[HttpPost]      
public ActionResult Create(Employee emp)      
{          
if (ModelState.IsValid)          
{             
 //Save the employee in DB first and then redirectToAction.
            return RedirectToAction("Index");          
    }
}

读:

  1. ASP.NET MVC3: ValidationType ModelClientValidationRule

  2. How does DataAnnotations really work in MVC?

  3. ASP.NET MVC 3 client-side validation with parameters

  4. http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

  5. Add Sorting and Searching in Contact Management ASP.NET MVC Application

  6. http://trainingkit.webcamps.ms/AspNetMvc.htm

  7. ValidationSummary and ValidationMessageFor with custom CSS shown when no errors present

  8. http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1

  9. What is the better ASP.NET MVC 3.0 Custom Validation approach

  10. http://dotnetslackers.com/articles/aspnet/Validating-Data-in-ASP-NET-MVC-Applications.aspx

2 个答案:

答案 0 :(得分:2)

您可以使用ModelState.AddModelError添加服务器端错误。如果ModelState包含错误,则会导致ModelState.IsValid为假。

[HttpPost]      
public ActionResult Create(Employee emp)      
{         
if (YourServerValidation(emp) == false) 
{
    ModelState.AddModelError("EmpName", "Invalid value");
}

if (ModelState.IsValid)          
{             
    //Save the employee in DB first and then redirectToAction.
    return RedirectToAction("Index");          
}
else
{ 
    return View(emp);
}

您的观点应更新如下:

<div>
    EmpName :~: @Html.TextBoxFor(model => model.EmpName)
    @Html.ValidationMessageFor(model => model.EmpName)
</div>

答案 1 :(得分:2)

您的模型可以实现IValidatableObject(内部System.ComponentModel.DataAnnotations namespace

您的模型应如下所示:

public class Employee : IValidatableObject
{

    public string EmployeeName;


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        char secondNameChar = EmployeeName[1];
        char thirdNameChar = EmployeeName[2];

        if (secondNameChar.ToString().ToLower() != "e")
            yield return
                new ValidationResult("Second char of name should be 'E'",
                                     new[] {"EmployeeName"});
        if (thirdNameChar.ToString().ToLower() != "f")
            yield return
                new ValidationResult("Third char of name should be 'F'",
                                     new[] {"EmployeeName"});


    }
}

请注意,将此员工的其他属性添加到此课程,并在Validate方法中进行验证。

现在在控制器上,如果您对无效对象调用ModelState.IsValid,则会失败并返回两个错误并将它们显示给用户。