Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当另一个模型值不为空时,数据注释是否需要一个值?_C#_Asp.net Mvc_Data Annotations - Fatal编程技术网

C# 当另一个模型值不为空时,数据注释是否需要一个值?

C# 当另一个模型值不为空时,数据注释是否需要一个值?,c#,asp.net-mvc,data-annotations,C#,Asp.net Mvc,Data Annotations,是否可以创建一个数据注释,允许我说如果QuestionType=“dropdown”那么SelectedValue是必需的 这是我的模型: public class QuestionViewModel { public int? Id { get; set; } public string QuestionType { get; set; } public string SubType { get; set; } public string Text { g

是否可以创建一个数据注释,允许我说如果QuestionType=“dropdown”那么SelectedValue是必需的

这是我的模型:

public class QuestionViewModel
{
    public int? Id { get; set; }

    public string QuestionType { get; set; }

    public string SubType { get; set; }

    public string Text { get; set; }

    public int SortOrder { get; set; }

    public bool IsHidden { get; set; }

    public int SelectedValue { get; set; }

    public List<QuestionOptionViewModel> Options { get; set; }
}
公共类问题视图模型
{
公共int?Id{get;set;}
公共字符串QuestionType{get;set;}
公共字符串子类型{get;set;}
公共字符串文本{get;set;}
公共int排序器{get;set;}
公共bool ishiden{get;set;}
public int SelectedValue{get;set;}
公共列表选项{get;set;}
}

我想说的是,如果问题类型是特定类型(下拉列表),则需要SelectedValue。

您可以创建一个自定义ValidationAttribute来诚实地执行任何操作。

只需从ValidationAttribute继承并编写所需的逻辑,然后将该属性丢弃到要有条件验证的属性上。标准的CompareAttribute与此非常相似。

首先,我认为如果你的问题类型是下拉列表,那么属性应该是
整数

完成后,应该使用
Html.DropdownListFor
为其设置验证

public class QuestionViewModel
{
    public int? Id { get; set; }

    [Required(ErrorMessage="Required")]
    public int QuestionType { get; set; }

    public string SubType { get; set; }

    public string Text { get; set; }

    public int SortOrder { get; set; }

    public bool IsHidden { get; set; }

    public int SelectedValue { get; set; }

    public List<QuestionOptionViewModel> Options { get; set; }
}

我明白了,这将是一个自定义的验证属性。是的,没有内置的注释,它使用了你的链接鞋并得到了我需要的东西。我应该关闭这个问题吗?不,让它作为一个重复关闭。实际上,QuestionType是一个字符串。他们将从数据库中输入“dropdown”。然后,我将从公共选项列表中取出这些选项的列表。selectedValue实际上是一个int?(我忘了加这个?)。我使用的是DropDownList for,所以不要为下拉列表设置任何默认值。这样总是选择一个选项。呃,这不是正确的处理方法。默认值是正确的方法,如果他们忘记使用下拉列表,请告知他们。我现在已经用自定义验证方法处理了这个问题。
List<SelectListItem> typeList=new List<SelectListItem>();
foreach(var type in questionTypes)
{
    typeList.Add(new SelectListItem{Text=type.Name,Value=type.QuestionTypeId.ToString()});
}
ViewBag.QuestionTypes=typeList;
@Html.DropdownListFor(model=>model.QuestionType,ViewBag.QuestionTypes,"--Select One--")
@Html.ValidationMessageFor(model=>model.QuestionType)