c# - ASP.NET MVC 显示成功消息

标签 c# asp.net-mvc

这是我从我的应用程序中删除记录的示例方法:

[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
    var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
    _db.DeleteObject(ArticleToDelete);
    _db.SaveChanges();

    return RedirectToAction("Index");
}

我想做的是在索引 View 上显示一条消息,内容如下:“Lorem ipsum 文章已被删除”我该怎么做?谢谢

这是我当前的 Index 方法,以防万一:

    // INDEX
    [HandleError]
    public ActionResult Index(string query, int? page)
    {
        // build the query
        var ArticleQuery = from a in _db.ArticleSet select a;
        // check if their is a query
        if (!string.IsNullOrEmpty(query))
        {
            ArticleQuery = ArticleQuery.Where(a => a.headline.Contains(query));
            //msp 2011-01-13 You need to send the query string to the View using ViewData
            ViewData["query"] = query;
        }
        // orders the articles by newest first
        var OrderedArticles = ArticleQuery.OrderByDescending(a => a.posted);
        // takes the ordered articles and paginates them using the PaginatedList class with 4 per page
        var PaginatedArticles = new PaginatedList<Article>(OrderedArticles, page ?? 0, 4);
        // return the paginated articles to the view
        return View(PaginatedArticles);
    }

最佳答案

一种方法是使用 TempData:

[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
    var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
    _db.DeleteObject(ArticleToDelete);
    _db.SaveChanges();
    TempData["message"] = ""Lorem ipsum article has been deleted";
    return RedirectToAction("Index");
}

Index 操作中,您可以从 TempData 获取此消息并使用它。例如,您可以将它作为 View 模型的属性传递,该属性将传递给 View ,以便它可以显示它:

public ActionResult Index()
{
    var message = TempData["message"];
    // TODO: do something with the message like pass to the view
}

更新:

例子:

public class MyViewModel
{
    public string Message { get; set; }
}

然后:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        Message = TempData["message"] as string;
    };
    return View(model);
}

在强类型 View 中:

<div><%: Model.Message %></div>

关于c# - ASP.NET MVC 显示成功消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684196/

相关文章:

c# - 在子类中更改静态变量而不在父类中更改它

asp.net-mvc - 我必须做什么才能从 MVC Controller 重定向到 Web 表单?

javascript - 如何在 XMLHttpRequest 中显示进度

c# - Linq 使用稍微复杂的选择列表

c# - 应用洞察监控

c# - 等待下载完成

C# - 使用 LINQ 将两个变量放入二维数组中?

c# - 从 MVVM 属性调用异步方法

asp.net - asp :datalist in asp.net-mvc 相当于什么

c# - 有约束的计划