Asp.net mvc 如何在MVC中管理视图中不同模型的视图(验证和绑定等)
假设用户可以创建销售广告(Post模型)。但是每一个广告都有不同的属性,这取决于它的类别。属性不确定,管理员可以使用不同的约束(必需的.MinLength等)添加属性 我定义了这样一个类:Asp.net mvc 如何在MVC中管理视图中不同模型的视图(验证和绑定等),asp.net-mvc,asp.net-mvc-5,Asp.net Mvc,Asp.net Mvc 5,假设用户可以创建销售广告(Post模型)。但是每一个广告都有不同的属性,这取决于它的类别。属性不确定,管理员可以使用不同的约束(必需的.MinLength等)添加属性 我定义了这样一个类: public class Property { public int Id { get; set; } public int Priority { get; set; } [Required()] public InputType Type { get; set; }
public class Property
{
public int Id { get; set; }
public int Priority { get; set; }
[Required()]
public InputType Type { get; set; }
[Required()]
[MaxLength(150)]
public string Title { get; set; }
[Index(IsUnique=true)]
[Required()]
[MaxLength(100)]
public string Values { get; set; }
[MaxLength(100)]
public string Description { get; set; }
public ICollection<GroupProperty> GroupProperties { get; set; }
public ICollection<PostProperty> PostProperties { get; set; }
}
public class MyClass{
public static void errorMessage(ModelStateDictionary ModelState) {
if (something) ModelState.AddModelError("", "Error Message");
}
}
公共类属性
{
公共int Id{get;set;}
公共int优先级{get;set;}
[必需()]
公共输入类型类型{get;set;}
[必需()]
[MaxLength(150)]
公共字符串标题{get;set;}
[索引(IsUnique=true)]
[必需()]
[MaxLength(100)]
公共字符串值{get;set;}
[MaxLength(100)]
公共字符串说明{get;set;}
公共ICollection组属性{get;set;}
公共ICollection后属性{get;set;}
}
例如,管理员可以将模型的汽车属性添加到汽车组。之后,用户必须填写模型车字段,以便在汽车组中进行广告
创建广告视图如下所示:
public class Property
{
public int Id { get; set; }
public int Priority { get; set; }
[Required()]
public InputType Type { get; set; }
[Required()]
[MaxLength(150)]
public string Title { get; set; }
[Index(IsUnique=true)]
[Required()]
[MaxLength(100)]
public string Values { get; set; }
[MaxLength(100)]
public string Description { get; set; }
public ICollection<GroupProperty> GroupProperties { get; set; }
public ICollection<PostProperty> PostProperties { get; set; }
}
public class MyClass{
public static void errorMessage(ModelStateDictionary ModelState) {
if (something) ModelState.AddModelError("", "Error Message");
}
}
@model IEnumerable
新广告
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
foreach(模型中的var项目)
{
@EditorFor(m=>item)
}
hvah
}
我想您应该创建一个类并验证ModelState
。你可以这样做-
例如:
您可以像这样传递模型状态:
public class Property
{
public int Id { get; set; }
public int Priority { get; set; }
[Required()]
public InputType Type { get; set; }
[Required()]
[MaxLength(150)]
public string Title { get; set; }
[Index(IsUnique=true)]
[Required()]
[MaxLength(100)]
public string Values { get; set; }
[MaxLength(100)]
public string Description { get; set; }
public ICollection<GroupProperty> GroupProperties { get; set; }
public ICollection<PostProperty> PostProperties { get; set; }
}
public class MyClass{
public static void errorMessage(ModelStateDictionary ModelState) {
if (something) ModelState.AddModelError("", "Error Message");
}
}
在控制器中使用:
MyClass.errorMessage(ModelState);
如果您需要更多关于外部modaestate验证的信息,那么您可以从链接获得更多帮助