ViewData not shown in Ajax.BeginForm

2019-08-03 01:43发布

问题:

I have creatd a partial view and inside it I am using AJAx.BeginForm. In Post Edit Action Method, I am adding VIEWDATA Like this

        if (ModelState.IsValid)
        {
            service.SaveAccount(account);
            TempData["message"] = "Account has been updated successfully!";

            AccountInfo accountInfo = new AccountInfo();
            accountInfo.AccountStatuses = service.GetAccountStatuses();
            accountInfo.AccountTypes = service.GetAccountTypes();
            accountInfo.CreditTerms = service.GetCreditTerms();
            return View("DisputeSubscriber", accountInfo);

        }
        else
        {
            return PartialView("_UpdateAccountDetails", account);
        }

and redirecting to same partial view. In partial view, I have added like this:

 @if (TempData["message"] != null)
                    {
                        <div class="Message">
                           I am here.
                            @TempData["message"]
                        </div>
                    }

but this message is not shows. this message is also inside AJAX.BeginForm. Please suggest

Do I need to redirect main view instead of partial view or there is something I am missing

回答1:

You seem to be using TempData and not ViewData which is not quite the same. Also you mentioned that you are using an Ajax.BeginForm to invoke this controller action. Since this is an AJAX call make sure that you have specified an UpdateTargetId in your AjaxOptions so that the resulting partial is injected somewhere into the DOM:

@using (Html.BeginForm(new AjaxOptions { UpdateTargetId = "foo" }))
{
    ...
}

<div id="foo"></div>