我在ASP.NET MVC3模型中有一個員工類。有一個名爲「EmpName」的字段。創建員工記錄有一個創建操作。應該有一個服務器端驗證 - 名稱的第二個字母應該是「E」,名稱的第三個字母應該是「F」。 (沒有客戶端驗證)。如果驗證失敗,則該消息應作爲驗證摘要顯示在創建視圖中。我們如何做到這一點?ASP.NET MVC3:創建操作的驗證摘要(服務器端驗證)
注意:這兩個驗證的驗證錯誤預計會出現兩個錯誤結果(兩個不同的行)。
注意:我沒有使用實體框架
以下是視圖代碼。
@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");
}
}
READING:
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
Add Sorting and Searching in Contact Management ASP.NET MVC Application
ValidationSummary and ValidationMessageFor with custom CSS shown when no errors present
http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1
What is the better ASP.NET MVC 3.0 Custom Validation approach
http://dotnetslackers.com/articles/aspnet/Validating-Data-in-ASP-NET-MVC-Applications.aspx
您是否在使用任何爲您創建實體的ORM?或者您創建了自己的POCO? – CjCoax 2012-02-19 06:10:02
我只是在學習MVC。我使用了我在控制器頁面中創建的Employee對象。我在另一個問題中發佈了類似的方法。請參閱http://stackoverflow.com/questions/9340093/asp-net-mvc3-object-from-dropdownlist-in-null-in-controller。另外,在真實情況下,我將使用WCF調用獲取數據庫值。我打算直接從控制器調用WCF服務。那是好方法嗎? – Lijo 2012-02-19 06:12:26
下面提到的方法適用於此嗎? http://stackoverflow.com/questions/9349766/asp-net-mvc3-validationtype-modelclientvalidationrule。 – Lijo 2012-02-19 14:37:41