Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show success message after insertion through form submitting

I want to show success message when insertion is complete.Here is my code

[HttpPost]
public ActionResult Create(string txthospitalname, int city)
{
    var hospitals = new Hospital()
    {
        Name = txthospitalname,
        FKCityID = city,
        CreatedAt = DateTime.Now,
        CreatedBy = 1,
    };
    _db.Hospitals.Add(hospitals);
    _db.SaveChanges();
    return RedirectToAction("Create");
}

View.cshtml

@using (Html.BeginForm("Create", "Hospital", FormMethod.Post, new {enctype = "multipart/form-data", id = "hospitalform"}))
{

    //Text Fields

}
like image 824
Khalid Zubair Avatar asked Oct 30 '25 07:10

Khalid Zubair


1 Answers

Using TempData is ideal for the Post-Redirect-Get pattern.

Your Post Action:

[HttpPost]
public ActionResult Create(string txthospitalname, int city)
{
    var hospitals = new Hospital()
    {
        Name = txthospitalname,
        FKCityID = city,
        CreatedAt = DateTime.Now,
        CreatedBy = 1,
    };
    _db.Hospitals.Add(hospitals);
    _db.SaveChanges();
    TempData["Success"] = true;
    return RedirectToAction("Create");
}

Your Get Action:

[HttpGet]
public ActionResult Create()
{
    ViewBag.Success = TempData["Success"] as bool;
    return View();
}

Your View:

@if (ViewBag.Success != null && ViewBag.Success)
{
    <h2> Your Success Message Here</h2>
}

@using (Html.BeginForm("Create", "Hospital", FormMethod.Post, 
    new {enctype = "multipart/form-data", id = "hospitalform"}))
{
    //Text Fields
}    
like image 146
ste-fu Avatar answered Oct 31 '25 21:10

ste-fu