2013-05-08 94 views
0

我沒有收到驗證消息?任何想法如何解決?請看下面的視圖,模型和控制器代碼。我還附加了js文件,可能是我缺少的文件?ASP.NET MVC中的模型驗證

@model MvcApplication1.Models.Assesment 
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> 
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> 
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> 

@using (Html.BeginForm()) 
{  
    @Html.TextBoxFor(m => m.name) 
    @Html.ValidationMessageFor(m=>m.name,"*Hello") 

} 
<input type="submit" value="submit" /> 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Web.Mvc; 
using System.ComponentModel.DataAnnotations; 

namespace MvcApplication1.Models 
{ 
    public class Assesment 
    { 
    [Required] 
    public string name { get; set; } 
    } 
} 

public class RegisterController : Controller 
{ 

    [HttpGet] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(Assesment assesment) 
    { 
     return View(); 
    } 
} 
+0

是這固定它 – user2224493 2013-05-08 15:38:36

+0

爲什麼您是否在表單之外提交輸入內容? – 2013-05-08 15:42:55

回答

0

<input type="submit">應該是在表單內。

此外,你應該處理POST

[HttpPost] 
public ActionResult Index(Assesment assesment) 
{ 
    return View(assesment); 
} 

時順便說無效的模型傳遞給視圖,典型的HttpPost動作看起來是這樣的:

[HttpPost] 
public ActionResult Index(Assesment assesment) 
{ 
    if(ModelState.IsValid) 
    { 
     // Handle POST data (write to DB, etc.) 
     //... 
     // Then redirect to a new page 
     return RedirectToAction(...); 
    } 

    // show the same view again, this time with validation errors 
    return View(assesment); 
}