【发布时间】:2014-08-26 04:12:31
【问题描述】:
我喜欢尝试使用我在此链接上发现的远程验证: 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 Controller 参数更改为(字符串 ms_person.email),但出现错误说找不到命名空间电子邮件。. 也尝试使用(字符串 ms_person_email),也不起作用
我也使用 student_code 进行了测试,student_code 字段可以正常工作,因为 student_code 属性在同一个模型中(ms_student),不像电子邮件(引用 ms_person)
所有元数据验证工作,就像两个模型都需要的一样,所以我猜错误是在 JsonResult 参数上
非常感谢
【问题讨论】:
-
你可以试试
public JsonResult CheckEmailExist([Bind(Prefix="ms_person"]string email) {.. -
试一试,但不起作用:O,正在寻找另一个解决方案..
-
刚测试,应该是
public JsonResult CheckEmailExist([Bind(Prefix="ms_person.email"]string email) {.. -
是的,工作得很好,我认为您在“]”之前缺少“)”,它应该是 JsonResult CheckEmailExist([Bind(Prefix="ms_person.email")]string email) Thx :D
-
当然可以(笨手笨脚的手指)。我会发布作为答案。
标签: c# asp.net-mvc validation