Home > Software engineering >  Get Id from new record in ASP.NET Core MVC
Get Id from new record in ASP.NET Core MVC

Time:11-29

I have the following action methods in my controller:

// GET: MenuOrders/Create
public IActionResult Create()
{
    ViewData["MasterMenuId"] = new SelectList(_context.MasterMenu, "MasterMenuId", "MasterMenuId");
    return View();
}

// POST: MenuOrders/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("MenuOrderId,CustomerName,MasterMenuId,OrderQty,IsPaid,IsCancel")] MenuOrder menuOrder)
{
        if (ModelState.IsValid)
        {
            _context.Add(menuOrder);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        ViewData["MasterMenuId"] = new SelectList(_context.MasterMenu, "MasterMenuId", "MasterMenuId", menuOrder.MasterMenuId);

        return View(menuOrder);
}

After I execute it, it will redirect to the Index page. I want to change it, so it will stay on the same view with the same data, including the Id (retrieved).

My question is: how can I do that?

Thank you

CodePudding user response:

I want to change it, so it will stay on the same view with the same data, including the Id (retrieved).

Well, you can do that in following way:

Controller:

Instead of this return RedirectToAction(nameof(Index)); You have to return to create view page and menuOrder.MenuOrderId will return us last inserted id. So the code would be as :

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("MenuOrderId,CustomerName,MasterMenuId,OrderQty,IsPaid,IsCancel")] MenuOrder menuOrder)
{
        if (ModelState.IsValid)
        {
            _context.Add(menuOrder);
            await _context.SaveChangesAsync();
            int lastInsertedId = menuOrder.MenuOrderId;
            ViewBag.lastensertedId = lastInsertedId ;
            return View("Create") ;
        }

        ViewData["MasterMenuId"] = new SelectList(_context.MasterMenu, "MasterMenuId", "MasterMenuId", menuOrder.MasterMenuId);

        return View(menuOrder);
}

Note: if you want to clear the existing form in that case you can use ModelState.Clear(); before return View("Create"). I have just provide you the last Inserted Id demo by binding in viewbag you can even bind that in your model as well.

View: In view you could set:

Output:

enter image description here

  • Related