[英]Model Validation in ASP.NET MVC
我没有收到验证消息吗? 任何想法如何解决? 请查看下面的视图,模型和控制器代码。 我还附加了js文件,也许我缺少文件?
@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();
}
}
您的<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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.