C# 模型中需要两个字段中的一个字段
我有一个情况,我想在模型中,只需要两个字段中的一个字段C# 模型中需要两个字段中的一个字段,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我有一个情况,我想在模型中,只需要两个字段中的一个字段 public int AutoId { get; set; } public virtual Auto Auto { get; set; } [StringLength(17, MinimumLength = 17)] [NotMapped] public String VIN { get; set; } 如果有人输入了vin,它将在控制器的AutoID上转换。如何强制控制器执行类似的操作
public int AutoId { get; set; }
public virtual Auto Auto { get; set; }
[StringLength(17, MinimumLength = 17)]
[NotMapped]
public String VIN { get; set; }
如果有人输入了vin,它将在控制器的AutoID上转换。如何强制控制器执行类似的操作
public ActionResult Create(Ogloszenie ogloszenie) {
information.AutoId = 1;
if (ModelState.IsValid)
{
...
}..
尝试使用这种方法: 控制器:
public ActionResult Index()
{
return View(new ExampleModel());
}
[HttpPost]
public ActionResult Index(ExampleModel model)
{
if (model.AutoId == 0 && String.IsNullOrEmpty(model.VIN))
ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
if (model.AutoId != 0 && !String.IsNullOrEmpty(model.VIN))
ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
if (ModelState.IsValid)
{
return null;
}
return View();
}
视图:
@使用(Html.BeginForm(null,null,FormMethod.Post))
{
@Html.ValidationMessage(“OftwoFieldsShouldbefilled”)
@Html.TextBoxFor(model=>model.AutoId)
@Html.TextBoxFor(model=>model.VIN)
}
尝试使用这种方法:
控制器:
public ActionResult Index()
{
return View(new ExampleModel());
}
[HttpPost]
public ActionResult Index(ExampleModel model)
{
if (model.AutoId == 0 && String.IsNullOrEmpty(model.VIN))
ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
if (model.AutoId != 0 && !String.IsNullOrEmpty(model.VIN))
ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
if (ModelState.IsValid)
{
return null;
}
return View();
}
视图:
@使用(Html.BeginForm(null,null,FormMethod.Post))
{
@Html.ValidationMessage(“OftwoFieldsShouldbefilled”)
@Html.TextBoxFor(model=>model.AutoId)
@Html.TextBoxFor(model=>model.VIN)
}
您可以实现一个自定义验证属性,该属性将检查是否存在任何必需字段
有关自定义验证属性的更多信息:您可以实现一个自定义验证属性,该属性将检查是否存在任何必需字段
关于自定义验证属性的更多信息:对不起,嗯,我有一个表单。在这个表单中,两个字段是。用户必须填写其中一个。需要填写一份。一个字段显示AutoID,另一个字段显示VIN。当用户填写AutoID时,一切正常。完成VIN后,ModelState.IsValid为false:(在检查ModelState AutoID字段是否已完成之前。抱歉,嗯,我有一个表单。在此表单中,两个字段。用户必须填写其中一个字段。需要填写一个字段。一个字段显示AutoID,另一个字段显示在VIN上。当用户填写AutoID时,一切正常。完成VIN时,ModelState.IsValid为false:(在检查ModelState AutoID字段是否完成之前。