3

Here's the Controller:

    [HttpPost]
    public async Task<ActionResult> Index(EmailService em)
    {

        if (ModelState.IsValid)
        {
            await em.Send();

        }
        return View(em);
    }

Here's the 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 the status updated correctly, meaning the data was "on it's way to the view as it should have been": "em" did have the data in it! On this statement.

 return View(em);

But the view remains in same state just prior to post? Notice the time stamp and the field below it?

enter image description here

Time to debug the packets, by pressing F12 on the browser on post with a break point set on entry to the controller so it won't respond... This is the inbound 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

This was value of "em" on way out setting break on controller's return View(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

Watching the 200 response from browser F12 Network side 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 the wrong copy to return after the Asynch controller method returned!

JWP
  • 6,672
  • 3
  • 50
  • 74

1 Answers1

3

Because when you return a view, the html helpers set the value of the controls from the values in ModelState, not the value in the model. The reason for that behavior is explained in this answer

In order to render the updated Sent and Status properties, you will 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);
}
Community
  • 1
  • 1
  • Thanks Stephen, I'll try this out today. – JWP Nov 25 '14 at 15:14
  • p.s. I just love MSFT documentation on this: http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary.clear(v=vs.118).aspx – JWP Nov 25 '14 at 15:26
  • Lab results showed this did the trick! Again thanks Stephen. – JWP Nov 25 '14 at 15:53