我正在使用万无一失的库来进行动态属性验证。
模型如下:
public class ProfileQuestion
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int QuestionTypeId { get; set; }
[RequiredIf("Isrequired", true, ErrorMessage = "Required")]
public string Answer { get; set; }
public string Day { get; set; }
public string Month { get; set; }
public string Year { get; set; }
public string Areacode { get; set; }
public string Zipcode { get; set; }
public List<ProfileOptions> OptionsList { get; set; }
public bool Isrequired = false;
}
我们有一个问题列表,其中一些问题是必需的。如果需要提问,请Isrequired = true
。我在模型状态验证之前设置了isrequired
标志,但是ModelState.IsValid
始终为假。
var mandatoryQuestions = objBusLayer.GetMandatoryQuestionIds(m);
foreach (ProfileQuestion question in Response)
{
if (question.QuestionId == 2)
{
string date = question.Year + @"/" + question.Month + @"/" +
question.Day;
DateTime outdate;
if (DateTime.TryParse(date, out outdate))
{
question.Answer = date;
}
}
if (question.QuestionId == 3)
{
question.Answer = question.Areacode + '-' + question.Zipcode;
}
if (mandatoryQuestions.Contains(question.QuestionId.ToString()))
{
question.Isrequired = true;
}
}
if (ModelState.IsValid)
{
Encryption encObj = new Encryption();
string decryptedExtPanelistId = encObj.DecryptText(e, password);
objBusLayer.Register(decryptedExtPanelistId, m, Response);
return RedirectToAction("Register", new { e = e, m = m, pg = pg + 1 });
}
ViewBag.pageId = pg;
ViewBag.extpnltid = e;
ViewBag.mid = m;
return View(Response);
我找不到问题,有人可以帮助我解决此问题吗?
答案 0 :(得分:0)
尝试结合使用ModelState.Clear()和TryValidateModel()。
ModelState.Clear();
TryValidateModel(Response);
致谢。