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.
ViewBag/ViewData: Can't be used since I returnRedirectToActionwhere I can't pass it in the URL instead of aView. I've considered usingAjaxto returnJSONinstead of usingRedirectToActionwhich would enable me to useViewBagbut this brings in some difficulties and would change the overall structure of the project.TempData: I don't have asessionconfigured in myStartup.csand can't do so since I'm missing theMicrosoft.AspNetCore.Sessionnamespace. 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>