As we all know that MVC stands for model view and
controller. Using JavaScript is one of the most challenging part. In my current article I have used MVC, C#.Net and JavaScript.
In my previous article I have shown you Bind
DataGridView In Windows Application Using C#, Digital
Clock in Asp.Net in C#, Asynchronous
Page Loading In Asp.net Using UpdatePanel and Timer Control | Simple
Asynchronous Page Load in ASP.NET.
So in this article I will show you how you can display the JavaScript
alert message in your MVC application.
In this article I will show you displaying alert message in two ways.
First how to display alert message on page load and second
how to display controller passed value in JavaScript
alert message.
So first we will create a new MVC application and add a controller. Now we will
create controller for the view. Here is the code for this controller and view.
Part1: Alert message on page load
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ProjectDemo_MVC.Controllers
{
public class HomeController
: Controller
{
/// <summary>
/// Display Alert message on page load in MVC application
using javasscript
/// </summary>
/// <returns></returns>
public
ActionResult Index()
{
return
View();
}
}
}
|
View:
@{
ViewBag.Title = "alert
message ";
}
<h2>This
is alert message om page load</h2>
<script language="javascript">
alert('@ViewData["Message"]');
</script>
|
Part2: Controller value in JavaScript alert message
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ProjectDemo_MVC.Controllers
{
public class HomeController
: Controller
{
/// <summary>
/// Display Alert message on page load in MVC application
using javasscript
/// </summary>
/// <returns></returns>
public
ActionResult Index()
{
ViewData["Message"]
= "This is value passed from
controller.";
return
View();
}
}
}
|
View:
@{
ViewBag.Title = "alert
mesage";
}
<h2>This
is alert message om page load</h2>
@if
(ViewData["Message"] != null)
{
<script language="javascript">
alert('@ViewData["Message"]');
</script>
}
|
In above code I have first checked whether any value present
in view or not. If value is present on that case we pass the value to
JavaScript.
Output
0 comments:
Please let me know your view