从控制器返回空模型对象以清除字段
本文关键字:清除 字段 对象 模型 控制器 返回 | 更新日期: 2023-09-27 18:32:45
在我的ASP MVC控制器中,我调用Web服务来处理一些信息。如果没有返回错误消息,那么我希望能够显示成功消息,但也重置整个字段。
我认为最好的方法是在错误消息上使用String.IsNullOrWhiteSpace()
,如果消息为空,则使用 new
语句擦除模型对象中的值,如下所示:
if (String.IsNullOrWhiteSpace(ViewBag.ErrorMessage))
{
agtPay = new AgentInformation();
}
return View(agtPay);
当我在 Visual Studio 中逐步执行代码时,视图中的字段似乎都按原样null
,但是当页面加载时,以前的值仍然存在。考虑到这与缓存有关,我将以下标签放在视图的顶部。
<meta http-equiv="PRAGMA" content="NO-CACHE">
下面是带有缩写switch
语句的视图中的代码:
[HttpPost]
public ActionResult AgentInformation(AgentInformation agtPay)
{
//redirect if security is not met.
if (!Security.IsAgent(User)) return RedirectToAction("Message", "Home", new { id = 1 });
try
{
//Run field validation and if anything found send back
string msg = AgentInformationValidator.ValidateFields(agtPay);
if (!String.IsNullOrWhiteSpace(msg))
{
ViewBag.ErrorMessage = msg;
return View(agtPay);
}
//If valid send agtPay to web service
AgentsClient webService = new AgentsClient();
ReturnMessage returnMessage = new ReturnMessage();
string userName = User.Identity.Name;
userName = userName.Substring(Math.Max(0, userName.Length - 6));
switch (agtPay.TransactionType)
{
case ("E"):
returnMessage = webService.EftUpdateByTaxid(true,
agtPay.RefNumType.ToString(),
agtPay.RefNumber,
agtPay.OwnerMasterAgentId,
agtPay.PaymentFrequency,
false,
agtPay.RoutingNumber,
agtPay.AccountType,
agtPay.AccountNumber,
REQUEST_SYSTEM,
userName);
break;
.
.
.
.
case ("U"):
returnMessage = webService.UnenrollEft(agtPay.RefNumType.ToString(),
agtPay.RefNumber,
agtPay.OwnerMasterAgentId,
REQUEST_SYSTEM,
userName);
break;
default:
ViewBag.ErrorMessage = "There was an error processing your request: No transaction type specified";
break;
}
if (returnMessage.Success)
{
string[] msgArray = returnMessage.FriendlyMsg.Split(';');
ViewBag.ReturnMessage = msgArray[0];
if (msgArray.Length > 0)
{
for (int i = 1; i < msgArray.Length; i++)
{
ViewBag.ErrorMessage += msgArray[i];
}
}
}
else
{
ViewBag.ErrorMessage = returnMessage.FriendlyMsg;
}
}
catch (Exception ex)
{
EventLog.WriteEntry("Monet", "From Agent Controller: 'n'r|Ex Message| " + ex.Message + "'n'r|Stack Trace| " + ex.StackTrace);
ViewBag.ErrorMessage = "An error has occurred, IT has been notified and will resolve the issue shortly!";
SendEmail.ErrorMail(ex);
}
if (String.IsNullOrWhiteSpace(ViewBag.ErrorMessage))
{
agtPay = new AgentInformation();
}
return View(agtPay);
}
这里的问题是初始请求是一个POST
,所以Razor
将从ModelState
中获取这些值。但是,您可以通过在返回之前发出此行来覆盖它:
ModelState.Clear();
完成此操作后,视图应从您发回的模型中提取值。
但是,我建议您更合适地发布RedirectToAction
,因为在我看来,您只是想回到GET
状态:
return RedirectToAction("AgentInformation");
而不是:
return View(agtPay);