c# - 如何在不返回 View() 的情况下在 MVC ASP.NET 中显示消息框

标签 c# asp.net asp.net-mvc asp.net-mvc-4

我是 stackoverflow 的新手,也是 asp.net 的新手 我想问一下如何在 mvc asp.net 中显示消息框。这是我的代码,但它会返回 NullReferenceException。感谢您的帮助。`

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult myfunction(MyViewModels myModel)
    {
        System.Web.UI.ScriptManager script_manager = new System.Web.UI.ScriptManager();

        if (ModelState.IsValid) {
            createRequest(myModel);
            script_manager.Page.ClientScript.RegisterStartupScript(this.GetType(), "showMyMessage", "ShowMessage('Requested Successfully.');", true);
            return RedirectToAction("GeneratePDF", "Forms", myModel);   
        }
        else
        {
            script_manager.Page.ClientScript.RegisterStartupScript(this.GetType(), "showMyMessage", "ShowMessage('Requested failed.');", true);
            return RedirectToAction("Index");
        }
    }`

最佳答案

做同样的事情有不同的方法,我添加了三种不同的方法,你可以根据不同的时间需要使用。

方式一:【针对你的需求推荐不返回view()】

public ContentResult HR_COE()
       {


           return Content("<script language='javascript' type='text/javascript'>alert     ('Requested Successfully ');</script>");
       }

内容结果类的官方定义:

表示作为操作方法结果的用户定义的内容类型。

来源: https://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.118).aspx

其他需要的有用示例: http://www.c-sharpcorner.com/UploadFile/db2972/content-result-in-controller-sample-in-mvc-day-9/

https://www.aspsnippets.com/Articles/ASPNet-MVC-ContentResult-Example-Return-String-Content-from-Controller-to-View-in-ASPNet-MVC.aspx

其他方式:

方式二: Controller 代码:

public ActionResult HR_COE()
       {
           TempData["testmsg"] = "<script>alert('Requested Successfully ');</script>";
           return View();
       }

查看代码:

@{
    ViewBag.Title = "HR_COE";
}

<h2>HR_COE</h2>

@if (TempData["testmsg"] != null)
{
   @Html.Raw(TempData["testmsg"]) 
}

方式三: Controller 代码:

public ActionResult HR_COE()
      {
          TempData["testmsg"] = " Requested Successfully ";
          return View();

      }

查看代码:

@{
    ViewBag.Title = "HR_COE_Without using raw";
}

<h2>HR_COE Without using raw</h2>

   @if( TempData["testmsg"] != null)
   {
<script type="text/javascript">
       alert("@TempData["testmsg"]");
</script>
   }

我亲自使用了所有三种方式,并得到了预期的输出。所以希望它一定会对您有所帮助。

请让我知道您的想法或反馈

谢谢 卡尔提克

关于c# - 如何在不返回 View() 的情况下在 MVC ASP.NET 中显示消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44037038/

相关文章:

c# - 如何使用迭代进行分组?

c# - 检查 List 中的 typeof(object) 是否为引用类型

c# - JSON 对象在使用 JsonResult 返回时被序列化为空括号

asp.net - 如何在 ASP.net Identity 2.0 上启用 AccessFailedCount 和锁定功能?

c# - ASP.NET MVC 路由

Jquery Rest 与 WCF 3.5 的通信

c# - SignalR:无法使用任何可用传输连接到服务器

asp.net - SignalR/signalr/hubs 404 未找到

JQuery Mobile 与 MVC 的链接

c# - 创建断开连接的数据库应用程序的最佳基于 .NET3.5 的策略