当用户选择超出允许范围的日期时,我必须显示验证消息。这是我必须使用的代码:
public ActionResult QuickEdit(int pk, string name, string value)
{
var freeOfChargeTime = Db.FreeOfChargeTime.Find(pk);
freeOfChargeTime.ProjectExtension = freeOfChargeTime.ProjectExtension ?? Db.ProjectExtensions.Find(freeOfChargeTime.ProjectExtensionId);
if ((name == "StartDate" && DateTime.Parse(value) > freeOfChargeTime.EndDate) || (name == "EndDate" && DateTime.Parse(value) < freeOfChargeTime.StartDate))
{
ModelState.AddModelError("StartDate", "the end date must be after the start date");
}
if (name == "NumberOfDays" && double.Parse(value) <= 0)
{
ModelState.AddModelError("NumberOfDays", "Number of days must be > 0");
}
if (name == "StartDate" && DateTime.Parse(value) < freeOfChargeTime.ProjectExtension.StartDate)
{
ModelState.AddModelError("StartDate", "the free of charge period start date must be after the project extension start date");
}
if (freeOfChargeTime.ProjectExtension is IPextWithEndDate)
{
var poWithEndDate = (IPextWithEndDate)freeOfChargeTime.ProjectExtension;
if (name == "EndDate" && DateTime.Parse(value) > poWithEndDate.EndDate)
{
ModelState.AddModelError("EndDate", "the free of charge period end date must be before the project extension end date");
}
}
if (freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Cancelled ||
freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Disabled)
{
ModelState.AddModelError("Status", "the project extension is cancelled or disabled");
}
if (ModelState.IsValid) return XEditableUpdate(Db.FreeOfChargeTime, pk, name, value);
Response.StatusCode = 400;
var error = new Error { Message = "Error: " + ModelState.Errors() };
return Json(error.Message, JsonRequestBehavior.AllowGet);
}
这会显示"Error: the free of charge period start date must be after the project extension start date\n"
我试过了:
@*#1*@
error.Message = error.Message.Split('\\').First();
@*#2*@
error.Message = error.Message.Replace("\\n", " ");
@*#3*@
string validationMessage = error.Message.Split('\\').First();
@*#4*@
string validationMessage = error.Message.Replace("\\n", " ");
@*#5*@
string validationMessage = error.Message;
validationMessage = validationMessage.Split('\\').First();
@*#6*@
string validationMessage = error.Message;
validationMessage = validationMessage.Replace("\\n", " ");
我仍然得到相同的结果。有没有办法摆脱“\ n”,或解决问题?
答案 0 :(得分:1)
validationMessage.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);
使用此代码。