Why is MVC Post (ViewModel) not returning an updated form using Async?
Here's the controller:
[HttpPost]
public async Task<ActionResult> Index(EmailService em)
{
if (ModelState.IsValid)
{
await em.Send();
}
return View(em);
}
Here ViewModel Send; where "this" is an instance of the EmailService class.
public async Task<EmailService> Send()
{
msg = new MailMessage(From, To);
msg.Body = Body;
msg.Subject = Subject;
SetHost();
try
{
await Server.SendMailAsync(msg);
status = Status.Success;
Sent = DateTime.Now;
return this;
}
catch (Exception iox)
{
status = Status.Failed;
IOX = iox;
return this;
}
}
I set a breakpoint here in the controller and saw that the state was updated correctly, which means the data was "on its way to the view, as it should be": the "em" did indeed contain data! About this statement.
return View(em);
But does the view stay in the same state just before publishing? Notice the timestamp and the box below it?
Time to debug packages by pressing F12 in the browser in a message with a breakpoint set when entering the controller so that it doesn't respond ... This is the input:
To:somebody@email.com
From:somebody@email.com
Subject:This is a test
Body:This is only a test
Sent:1/1/0001 12:00:00 AM
status:Initialized
This is the "em" value when exiting break mode on return of the View controller (em):
To:somebody@email.com
From:somebody@email.com
Subject:This is a test
Body:"This is only a test" string
Sent:{11/24/2014 6:48:49 PM}
status:Success
Observing a 200 response from the F12 Network browser showed this "old" form data!
To:somebody@email.com
From:somebody@email.com
Subject:This is a test
Body:This is only a test
Sent:1/1/0001 12:00:00 AM
status:Initialized
Any help would be appreciated, it looks like MVC pulled out the wrong copy to return after returning the Asynch controller method!
source to share
Because when you return the view, the html helpers set the controls' value from values ββto ModelState
, not the value in the model. The reason for this behavior is explained in this answer
To display updated properties Sent
and Status
, you need to clear ModelState
for those properties.
[HttpPost]
public async Task<ActionResult> Index(EmailService em)
{
if (ModelState.IsValid)
{
ModelState.Clear(); // or `ModelState.Remove("Sent"); ModelState.Remove("Status")`
em = await em.Send();
}
return View(em);
}
source to share