【问题标题】:Return View with Query strings使用查询字符串返回视图
【发布时间】:2018-07-20 08:09:12
【问题描述】:

您好,我在控制器中设置了一个方法,可以将一些数据保存到一个组中。

当用户再次尝试保存到该组时,它会返回错误并返回视图。但是,由于我使用的是查询字符串,因此我想返回视图并将查询字符串添加到 URL。

        public async Task<IActionResult> Create([Bind("Id,GroupId,PayCompId,Client")] PayComponentGrouping payComponentGrouping)
    {
        string referer = Request.Headers["Referer"].ToString();

        var GroupId = payComponentGrouping.GroupId;
        var PayId = payComponentGrouping.PayCompId;
        var Db = payComponentGrouping.Client;

        if (ModelState.IsValid)
        {
            IList<PayComponentGrouping> items = _context.PayComponentGrouping
                .Where(o => o.GroupId == GroupId)
                .Where(o => o.PayCompId == PayId)
                .Where(o => o.Client == Db)
                .ToList();

            var GroupName = _context.payComponentGroups
                                .Where(o => o.GroupId == GroupId)
                                .Select(o => o.GroupName)
                                .FirstOrDefault();

            if (items.Count == 0)
            {
                _context.Add(payComponentGrouping);
                await _context.SaveChangesAsync();
                return RedirectToAction("Details", "DatabaseLists", new { id = Db });
            }

            ViewBag.Error = $"Already belongs to Group: {GroupName}";

        }

        return View();
    }

所以在返回 View() 中我想添加 PayId 和 Db。我最初使用 return Redirect(referer) 将用户重定向到带有查询字符串的页面。由于它是重定向,因此不会出现错误消息。

【问题讨论】:

    标签: c# asp.net-mvc model-view-controller asp.net-core-2.0


    【解决方案1】:

    我想通了。

    我将 ViewBag 更改为 TempData,然后返回重定向。

    TempData["Error"] = $"Already belongs to Group: {GroupName}";
    
    return Redirect(referer);
    

    错误消息随后被添加到视图中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多