技术开发 频道

MVC框架开发Web论坛之另类表单校验篇

  请注意到,这个Validate()方法调用了另一个GetRuleViolations()方法。如果存在任何校验错误,那么该Validate()方法即抛出一个RuleViolationException型异常。

  在论坛应用程序中,该Validate()方法是在ForumRepository中被调用的。在把一个新消息添加到数据库中之前,在Message类上调用这个Validate()方法,如下所示:
 

public Message AddMessage(Message messageToAdd)

{

  messageToAdd.Validate();

  _dataContext.Insert(messageToAdd);

  
return messageToAdd;

}

   如果存在一个校验错误,那么将抛出一个RuleViolationException型异常,并且永不会把相应的消息插入到数据库中。
该ForumRepository应用于论坛控制器内。当你提交一个表单用以创建一个新的论坛消息时,ForumController.Create(FormCollection collecction)方法即被调用。列表6中提供了论坛控制器完整的实现代码。
  列表6–ForumController.cs
 

using System;
using System.Web.Mvc;
using MvcForums.Models;
using Microsoft.Web.Mvc;
using MvcForums.Models.Entities;
using MvcValidation;

namespace MvcForums.Controllers
{
    
public class ForumController : Controller
    {
        
private IForumRepository _repository;

        
public ForumController()
            :
this(new ForumRepository())
        { }

        
public ForumController(IForumRepository repository)
        {
            _repository
= repository;
        }

        
public ActionResult Index()
        {
            ViewData.Model
= _repository.SelectThreads();
            
return View("Index");
        }

        [AcceptVerbs(
"GET")]
        
public ActionResult Create()
        {
            
return View("Create");
        }

        [AcceptVerbs(
"Post")]
        
public ActionResult Create(FormCollection form)
        {
            var messageToCreate
= new Message();

            
try
            {
                UpdateModel(messageToCreate,
new[] { "Author", "ParentThreadId", "ParentMessageId", "Subject", "Body" });
                _repository.AddMessage(messageToCreate);
            }
            
catch (RuleViolationException rex)
            {
                Validation.UpdateModelStateWithViolations(rex, ViewData.ModelState);
                
return View("Create", messageToCreate);
            }
            
catch (Exception ex)
            {
                ViewData.ModelState.AddModelError(
"message", null, "Could not save message.");
                
return View("Create", messageToCreate);
            }

            
// Redirect
            return RedirectToAction("Index");
        }

        
public ActionResult Thread(int threadId)
        {
            ViewData.Model
= _repository.SelectMessages(threadId);
            
return View("Thread");
        }

    }
}

  注意,这里存在两个Create()方法。第一个Create()方法仅当发生一次HTTP GET操作时才被调用。这个行为返回的表单将用于创建一个新的消息

0
相关文章