如何在mvc3中自定义验证模型类? [英] how to custom validate your model class in mvc3?

查看:55
本文介绍了如何在mvc3中自定义验证模型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在构建Mvc应用程序,但遇到了问题.
我有一个模型类,其中所有字段都是必需的

Hi,

I am building a Mvc application and got stucked in a problem .
I have a model class where all the fields are required as such

public class NewChart
   { [Required(ErrorMessage = "*")]
       [Display(Name = "Date Of Service")]
       public DateTime DateOfService { get; set; }

       [Required(ErrorMessage = "*")]
       [Display(Name = "Encounter Number")]
       public int EncounterNumber { get; set; }

       [Required(ErrorMessage = "*")]
       [Display(Name = "Encountered Date")]
       public DateTime EncounteredDate { get; set; }

       [Required(ErrorMessage = "*",AllowEmptyStrings=true)]
       [Display(Name = "Discharge Date")]
       public DateTime DischargeDate { get; set; }

       [Required(ErrorMessage = "*")]
       [Display(Name = "Record Unique ID")]
       public string RecordID { get; set; }

       [Required(ErrorMessage = "*")]
       [Display(Name = "Scan Date")]
       public DateTime ScanDate { get; set; }

   }



我有一个像这样的下拉列表,其中有五个数据,这些数据是使用linq to sql动态填充的.我没有dropdownlist的单独模型类.例如,下拉列表中的值为ä","b","c","d","e".我需要自定义验证必填字段.我不想在模型类中删除所需的字段验证器,而是想对其进行修改.我的问题是,如果我从下拉列表中选择"a",那么出院日期的验证必须是有条件的.如果我要在此字段中保存过期日期,则不得调用必需的字段验证器.

我不想删除模型中的必填字段,因为除了"a"之外,在提交表单之前我还需要其他所有必填字段.我想在此特定字段中发送null或日期.



and i have a drop down list like that has five data which is dynamically populated using linq to sql. I do not have seprate model class for dropdownlist . For instance the value in dropdown list are "ä","b","c","d","e" . I need to custom validate the required field . I dont want to remove the required field validator in model class rather want to modify it. my problem is if i select "a" from drop downlist then the validation for discharge date must be conditional . this must not invoke the required field validator if i want to save it with out passing date in this field.

I didnot wanted to remove the required field in model because i need other all the fields to be required before the form is submitted except "a" . I want to send either null or date in this particular field.

how do i achieve this?

推荐答案

从您的控制器执行此操作.
使用
过滤那里的值
Do this from your controller..

filter the values there using

if (modelObj.NamedValue!="a")
{
    //your code goes here
else
{
    ModelState.AddModelError("Show this error");
}


这篇关于如何在mvc3中自定义验证模型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆