【发布时间】:2018-11-23 02:02:55
【问题描述】:
情况
在我的 ASP.NET 项目中,我有一个允许用户更改密码的视图。提交表单后,用户将使用RedirectToAction 重定向到 UserDetail。这里我想通知用户密码更改是否成功(计划使用Alertify JS)。然而,我似乎无法成功地将消息从我的控制器传递到我的视图。
当使用RedirectToAction 而不使用ViewBag、ViewData、Tempdata...时,如何正确地将数据(简单字符串)从控制器传递到视图?或者,如果有办法解决我目前遇到的这些问题,很高兴听到。
-
李>ViewBag/ViewData:无法使用,因为我返回RedirectToAction无法在 URL 中传递它而不是View。我曾考虑使用Ajax来返回JSON,而不是使用RedirectToAction,这将使我能够使用ViewBag,但这会带来一些困难并且会改变项目的整体结构。 TempData:我的Startup.cs中没有配置session,因为我缺少Microsoft.AspNetCore.Session命名空间,所以无法这样做。我也无法添加命名空间,因为这会增加一些复杂性。看到以下错误: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.'
我宁愿不使用 cookie 或某种兑现系统。
编辑:我也宁愿不使用查询字符串,但看到 cmets/answers 让我意识到我的选项是有限的。我之前忘记将查询字符串/路由参数添加到列表中。
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>
【问题讨论】:
-
为您的视图模型添加一个
string Message属性 -
您可以将其作为路由参数
new { id = model.UserId, message= "" }传递并在UserDetail(int id, string message)中接受它 -
感谢大家的cmets。我宁愿不使用查询字符串/路由参数,但似乎我的选择有限。尽管@StephenMuecke,我还有一个关于模型更改的问题,即使我更改了模型,我实际上也没有将它传递给 YserDetail,对吧?
-
@WouterVanherck 我宁愿考虑修复 TempData 问题,也不愿提出这个问题,因为如果您要修复 TempData,您将有很多选项可以实现。如果 TempData 运行正常,我会找到一个好的解决方案。
标签: c# asp.net asp.net-mvc