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?

enter image description here

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!

+3


source to share


1 answer


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);
}

      

+3


source







All Articles