简体   繁体   English

ASP.NET:将消息从控制器传递到视图(ViewBag,ViewData或TempData)

[英]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. 在我的ASP.NET项目中,我具有一个允许用户更改其密码的视图。 After submitting a form, the user will be redirected to the UserDetail using RedirectToAction . 提交表单后,将使用RedirectToAction将用户重定向到UserDetail。 Here I want to notify the user if the password change was successful or not (planning to use Alertify JS ). 在这里,我想通知用户密码更改是否成功(计划使用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 , ...? 当使用RedirectToAction而不使用ViewBagViewDataTempdata ,...时,如何正确地将数据(简单字符串)从控制器传递到视图? 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 . ViewBag / ViewData :无法使用,因为我返回了RedirectToAction ,我无法在URL而不是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. 我已经考虑过使用Ajax返回JSON而不是使用RedirectToAction ,这将使我能够使用ViewBag但这会带来一些困难,并会改变项目的整体结构。

  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. TempData :我没有在Startup.cs配置session ,也不能这样做,因为我缺少Microsoft.AspNetCore.Session命名空间。 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.' 请参见以下错误: 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. 我宁愿不使用Cookie或某种现金系统。
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. 我忘记了将querystring / route参数添加到较早的列表中。

The ManageController.cs 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 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>

You can pass it as route parameter with RedirectToAction() method 您可以使用RedirectToAction()方法将其作为路由参数传递

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);
}

About another options as your described, i would suggest SessionState: 关于您所描述的另一个选项,我建议使用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. 或创建一个JsonResult结果来引用一个Ajax调用。

change: 更改:

[HttpGet]
public IActionResult UserDetail(int id)

to

[HttpPost]
public IActionResult UserDetail(UserViewModel model)

Add the Message property to your model. 将Message属性添加到模型中。

should do it for you 应该为你做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM