Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return View with Query strings

Hello I have a method set up in my controller which saves some data into a group.

When a user tries to save to that group again it returns an error and goes back to the view. However since I am using query strings I would like to return the view and add a query string to the 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();
    }

So in the return View() I would like to add the PayId and Db. I initially used return Redirect(referer) which redirected the user to the page with query strings. Since it is a redirect no error message appears.

like image 774
theJ Avatar asked Jun 23 '26 11:06

theJ


1 Answers

I have figured it out.

I changed my ViewBag to TempData and then returned the redirect.

TempData["Error"] = $"Already belongs to Group: {GroupName}";

return Redirect(referer);

The error message was then added to View.

like image 159
theJ Avatar answered Jun 25 '26 01:06

theJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!