【问题标题】:How to show success message after insertion through form submitting通过表单提交插入后如何显示成功消息
【发布时间】:2016-05-04 06:27:19
【问题描述】:

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

[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

}

【问题讨论】:

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


    【解决方案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
    }    
    

    【讨论】:

    • $(document).ready(function () { if ('@ViewBag.Success' == "添加") { toastr.success("医院添加成功"); } });
    • 在脚本中添加此代码后,它对我很有用。谢谢亲爱的。
    • 对于 ASP.NET 4.8,您需要将 GET 操作中的 Success 行设为可空类型:ViewBag.Success = TempData["Success"] as bool?;。见:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多