使用远程验证asp.net MVC
本文关键字:asp net MVC 验证 程验证 | 更新日期: 2023-09-27 18:19:21
我喜欢尝试使用远程验证,我发现这个链接:http://www.youtube.com/watch?v=Ll8VtDRj8L4
我已经按照指令,它的工作,但问题是,当我试图从引用表中添加数据,验证不会工作
模型类:
public partial class ms_student
{
public int ID { get; set; }
public string student_code{ get; set; }
public virtual ms_person ms_person { get; set; }
}
public partial class ms_person
{
public string name{ get; set; }
public string email { get; set; }
public virtual ms_student ms_student { get; set; }
}
元数据:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Test.Models
{
[MetadataType(typeof(personMD))]
public partial class ms_person
{
}
public class personMD
{
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[Remote("CheckEmailExist", "Administrator", ErrorMessage = "Email Already Exist")]
public object email { get; set; }
}
}
控制器:
public JsonResult CheckEmailExist(string email) // the error i think from email paramater, cause the video said to make the paramater exactly the same name...
{
return Json(!db.ms_person.Any(m => m.email == email), JsonRequestBehavior.AllowGet);
}
视图:
@model Test.Models.ms_student
@using (Html.BeginForm("CreateStudent", "Administrator", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.TextBoxFor(model => model.student_code) //this one work and already tested
@Html.ValidationMessageFor(model => model.student_code)
@Html.TextBoxFor(model => model.ms_person.email) //if you inspect element on browser the NAME are ms_person.email and ID are ms_person_email
@Html.ValidationMessageFor(model => model.ms_person.email)
}
我试图改变JsonResult控制器参数为(字符串ms_person.email),但有错误说命名空间电子邮件找不到。还尝试使用(string ms_person_email),也不工作
我也测试了使用student_code, student_code字段工作正常,因为student_code属性是在同一个模型(ms_student),不像电子邮件(引用ms_person)
所有元数据验证工作,就像需要在两个模型上,所以我猜错误是在JsonResult参数
非常感谢
修改动作方法,使其包含Bind Prefix
属性/属性
public JsonResult CheckEmailExist([Bind(Prefix="ms_person.email")]string email)
{
...
直接改成
@Html.TextBoxFor(model => model.ms_person.email, new{@id="email", @name="email"})