从控制器到视图的成功消息 [英] Success message from Controller to View

查看:71
本文介绍了从控制器到视图的成功消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在添加某些用户时在我的视图中显示一些消息.

I want to display in my view some message when some user is added.

当我们的模型出现问题时,可以使用一种方法(ModelState.AddModelError)处理不成功的消息.但是,当一切正常时,我们如何处理给用户的信息,说明他的操作成功了?

When something goes wrong in our model, there is a method (ModelState.AddModelError) to handle unsuccessful messages. But, when the things go okay, how can we handle a message to the user saying that his action was a success?

我发现此线程提供了解决方案,但大约需要三年通过了,我需要知道:没有别的办法了,也许更成熟了吗?不是不是这样,但是我们仍然以同样的方式处理成功的讯息吗?

I found this thread that provides a solution, but about three years passed and I need to know: there's not another way, perhaps more mature? Not that this is not, but we still deal with messages of success on this same way?

推荐答案

有几种方法可以给这只猫蒙皮.您可以使用ViewBag:

There are a few ways to skin this cat. You could use the ViewBag:

ViewBag.SuccessMessage = "<p>Success!</p>";

然后在您的视图中可以将其呈现到页面:

Then in your view you could render it to the page:

@ViewBag.SuccessMessage

我不是ViewBag的粉丝,因此通常创建一个ViewModel对象,该对象包含我特定视图所需的所有数据.成功消息就是那种数据:

I'm not a fan of the ViewBag, so I typically have a ViewModel object created that holds all the data I would need for my particular view. And a success message would be just that kind of data:

public MyViewModel{
    public bool IsSuccess {get;set;}
}

然后在您的控制器中,您可以将此ViewModel传递给您的同类型视图

Then in your controller, you would pass this ViewModel to your stongly-typed view

[HttpPost]
public ActionResult Update(MyViewModel vm){
    //Glorious code!

   return View(vm)
}

最后,只需在您的视图中检查它,如果成功则打印一条消息:

Finally, just check it in your view and print a message if it succeeds:

@if(vm.IsSuccess){
     <p>Here is an amazing success message!</p>
}

此外,您还可以使用TempData,它的工作原理类似于ViewBag,但仅持续到下一个请求结束时才被丢弃:

Also, instead of that, you can use TempData, which works like the ViewBag but only lasts until the end of your next request and is then discarded:

TempData["SuccessMessage"] = "Success!";

这篇关于从控制器到视图的成功消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆