如何在MVC ASP.NET中显示消息框而不返回View()

Mik*_*ike 2 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");
        }
    }`
Run Code Online (Sandbox Code Playgroud)

Kar*_*lai 9

有不同的方法可以做同样的事情,我已经添加了三种不同的方式,您可以使用,无论您在不同的时间需要什么.

方式1:[建议您的要求没有返回视图()]

public ContentResult HR_COE()
       {


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

内容结果类的官方定义:

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

来源: 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

其他方法:

方式2: 控制器代码:

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

查看代码:

@{
    ViewBag.Title = "HR_COE";
}

<h2>HR_COE</h2>

@if (TempData["testmsg"] != null)
{
   @Html.Raw(TempData["testmsg"]) 
}
Run Code Online (Sandbox Code Playgroud)

方式3: 控制器代码:

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

      }
Run Code Online (Sandbox Code Playgroud)

查看代码:

@{
    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>
   }
Run Code Online (Sandbox Code Playgroud)

我亲自使用了所有这三种方式,并按预期得到了输出.所以希望它对你有用.

请告诉我您的想法或反馈

谢谢Karthik