我是 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/
其他方式:
方式二: 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/