如何通过表单提交插入后显示成功消息

时间:2016-01-27 10:41:26

标签: javascript jquery asp.net-mvc model-view-controller

我希望在插入完成后显示成功消息。这是我的代码

[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

}

1 个答案:

答案 0 :(得分:1)

使用TempDataPost-Redirect-Get模式的理想选择。

你的邮政行动:

[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");
}

你的行动:

[HttpGet]
public ActionResult Create()
{
    ViewBag.Success = TempData["Success"] as bool;
    return 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
}