Wouter Vanherck
Wouter Vanherck

Reputation: 2308

ASP.NET: Pass message from controller to view (ViewBag, ViewData or TempData)

Situation

Inside my ASP.NET project, I have a view which allows the user to change his password. After submitting a form, the user will be redirected to the UserDetail using RedirectToAction. Here I want to notify the user if the password change was successful or not (planning to use Alertify JS). Yet, I can't seem to successfully pass the message from my controller to my view.

How does one properly pass data (simple string) from a controller to a view when using RedirectToAction without the use of ViewBag, ViewData, Tempdata, ...? Or, if there's a way to solve my current difficulties with these, happy to hear.

  1. ViewBag/ViewData: Can't be used since I return RedirectToAction where I can't pass it in the URL instead of a View. I've considered using Ajax to return JSON instead of using RedirectToAction which would enable me to use ViewBag but this brings in some difficulties and would change the overall structure of the project.

  2. TempData: I don't have a session configured in my Startup.cs and can't do so since I'm missing the Microsoft.AspNetCore.Session namespace. I also can't add the namespace since this adds some complications. See the following error: System.TypeLoadException: 'Method 'ConfigureAppConfiguration' in type 'Microsoft.AspNetCore.Hosting.WebHostBuilder' from assembly 'Microsoft.AspNetCore.Hosting, Version=1.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.'

I'd rather not work with cookies or some sort of cashing system.
EDIT: I'd also rather not use a querystring but seeing the comments/answers makes me realize that my options are limited. I forgot to add the querystring/route param to the list earlier.

The ManageController.cs

[HttpGet]
public IActionResult UserDetail(int id)
{
    // Code to GET the UserViewModel
    return View(model);
}

[HttpGet]
public IActionResult UserPassword(int id)
{
    // Code to GET the UserViewModel
    return View(model);
}

[HttpPost]
public IActionResult UserPassword(UserViewModel model)
{
    // Code to check and save the password.
    if (user.Password == model.Password) {
        //ViewData["Message"] = "Succeeded";
        //TempData["Message"] = "Succeeded";
    } else {
        //ViewData["Message"] = "Failed";
        //TempData["Message"] = "Failed";
    }
    // TODO: Alert the user
    return RedirectToAction("UserDetail", new { id = model.UserId });
}

UserDetail.cshtml

<!-- Some view code -->
<form>
    <button class="ui button button-back" type="button" onclick="window.location.href = '@Url.Action("UserPassword", "Manage", new { id = Model.UserId })';">Change Password</button>
</form>
<!-- Trying to use ViewData -->
@*<div id="id-message" data-value="@ViewData["Message"]"></div>*@

<script>
  $(document).ready(function () {
    console.log("Ready");

    // Alert the user of a password change
    //var message = $("#id-message").attr("data-value");
    //var message = "@(TempData["Message"] as string)";
    if (message !== null && message !== "") {
      alertify
        .alertmessage, function () {
          alertify.message('OK');
        };
    }
  });
  // Some script code
</script>

Upvotes: 0

Views: 1510

Answers (3)

Ibrahim Malluf
Ibrahim Malluf

Reputation: 657

change:

[HttpGet]
public IActionResult UserDetail(int id)

to

[HttpPost]
public IActionResult UserDetail(UserViewModel model)

Add the Message property to your model.

should do it for you

Upvotes: 0

user8207463
user8207463

Reputation:

About another options as your described, i would suggest SessionState:

string passwordChange = "Password has been changed";
Session["yourName"] = passwordChange  // inside your if else logic calling it from your UserDetail controller method. 

Or creating a JsonResult result to reference an Ajax call, for instance.

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You can pass it as route parameter with RedirectToAction() method

return RedirectToAction("UserDetail", new { id = model.UserId, message= "" });

and accept it

[HttpGet]
public IActionResult UserDetail(int id, string message)
{
   // Code to GET the UserViewModel
   return View(model);
}

Upvotes: 1

Related Questions