How to Show Alert Message in MVC 4 Controller

How to show alert message in mvc 4 controller?

You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.

You therefore need to use javascript when the response returns to show a messagebox of some sort.

OR

using jquery on the button that calls the controller action

<script>
$(document).ready(function(){
$("#submitButton").on("click",function()
{
alert('Your Message');
});

});
<script>

how to display alert message in controller

Basically that depends on how are you inserting the value into the database, as you would need a method to tells you whether the insertion was successful. As there's a few ways to do that now, linq/entity framework/sql/etc.

Then after you know whether did the insertion happens, then you can just assign a value to a variable and then from the code/aspx just check the value and do a simple alert.

<script type="text/javascript">
//i'm using jquery ready event which will call the javascript chunk after the page has completed loading
$(document).ready(function(){
//assuming that your variable name from the code behind is bInsertSuccess
var bSuccess = "<%= bInsertSuccess %>";
if(bSuccess){
alert("Successfully Inserted");
}
});
</script>

Display Alert Message: On OK button click RedirectToAction

You can convert your form submit to be an ajax form submit and return a JSON response back from your action method. In your ajax call's success event, you can show the message to user and then do a redirect using javascript.

You can use the below jQuery code to ajaxify your form submit.

$(function() {

$("form").submit(function(e) {
e.preventDefault();
var f = $(this);
$.post(f.attr("action"), f.serialize(),function(res) {
if(res.Status==="success")
{
alert(res.Message);
window.location.href="your new url here";
}
});
});

});

and have your action method updated to return json response

[HttpPost]
public ActionResult Save(string submit, Models.KnownIssues knownIssue)
{
// your code
if (Request.IsAjaxRequest())
{
return Json(new {Status = "success", Message="Succesfully updated"});
}
return RedirectToAction("Index");
}

Another option is to Show the message on the next page. For this, you can use your current form submit approach (no need of ajax) and use TempData to store the message. In the next action method, read the TempData in the view and show the message to user. Take a look at the below post for sample code

Display message in a toastr after controller method finish

Custom alert message in asp.MVC

You can use the TempData[""] to check the status of your create/update method and if the TempData[""] is having some value then you can display what you wanted to display

public ActionResult Create([Bind(Include = "Id,SuppName,Pay_Method,Status,Create_By,Create_Date")] M_Supplier m_Supplier)
{
if (ModelState.IsValid)
{
m_Supplier.Create_By= int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
m_Supplier.Status = true;
m_Supplier.Create_Date = DateTime.Now;
db.M_Supplier.Add(m_Supplier);
db.SaveChanges();
TempData["msg"]="success";

return RedirectToAction("Index");
}
TempData["msg"]="error";
return View(m_Supplier);
}

and now you can check the value of TempData["msg"] on your view

       //Check parameter here and display Message
@if (TempData["msg"] !=null)
{
if(TempData["msg"].ToString()=="success"){
<div class="alert alert-success alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Record Added Successfully.</strong>
</div>
}
}

Or something what you have done is

@Html.ActionLink("Back to List", "Index")

@{
if (TempData["msg"] !=null)
{
if(TempData["msg"].ToString()=="success"){
<div class="alert alert-success alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Record Added Successfully.</strong>
</div>
}

}

}

How to display an alert message from .cshtml view - asp.net mvc

You could check with some simple Razor syntax

@if(!string.IsNullOrEmpty(Model.Property1)) {
<script>alert("@Model.Property1");</script>
}

How to pass alert or notification message from controller to View?

You can use ViewBag or ViewData instead of TempData. Another approach is; you can use Session also.
If this doesnot solve your problem, please check below links, I hope you will find your solution.

Any reason why my ViewBag is not working?

MVC 5 asp.net, viewbag from controller to view is not working

How to display alert message box in asp.net core mvc controller?

Define the error in your controller:

ModelState.AddModelError("Error", "Check ID");

And then display it in the view:

@if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0)
{
<div class="alert alert-
<strong>Error!</strong> danger">@ViewData.ModelState["Error"].Errors.First().ErrorMessage
</div>
}

EDIT

To show an alert box, add some javascript in your view, the following uses jquery:

<head>
<script type="text/javascript">
@if (!ViewData.ModelState.IsValid && ViewData.ModelState["Error"].Errors.Count > 0)
{
<text>
$(document).ready(function() {
alert('@ViewData.ModelState["Error"].Errors.First().ErrorMessage');
});
</text>
}
</script>
</head>

Return alert/message in asp.net MVC from controller without Ajax?

You can store the message to be shown in the TempData (inside your controller in the error case). Then return a view to be shown.

public const string FlashMessageTempDataKey = "_flash";
controller.TempData[FlashMessageTempDataKey] = "The Message (Grandmaster Flash and the Furious Five)";

And then check whether the TempData is present in your view.

public static MvcHtmlString Flash(this HtmlHelper helper) {
var message = helper.ViewContext.Controller.TempData[FlashMessageTempDataKey] as string;
var sb = new StringBuilder();
if (message != null) {
sb.AppendLine("<script>");
sb.AppendLine("$(function() {");
sb.AppendFormat("flash('{0}');", HttpUtility.JavaScriptStringEncode(message));
sb.AppendLine("});</script>");
}
return MvcHtmlString.Create(sb.ToString());
}

Use this extension method as @Html.Flash(), e.g. in your _layout.cshtml. It assumes that there is some global JS function flash(message) and jQuery available on the page to display the message.

function flash(message) {
alert(message);
}

Note that with this mechanism, the message will be shown on the next page the user loads, which must not necessarely be the page that triggered the error (e.g. if he has multiple browser tabs open).



Related Topics



Leave a reply



Submit