How to display alert message in view page using viewbag - javascript

In Cshtml the following doesn't work
ViewBag.alert = #"<script language='javascript'>alert('Plan Already Exists');</script>";
How can i achieve this

I am using MVC Razor with C#, and I got this logic to work in my view by updating it a bit:
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<script type="text/javascript">
alert("#ViewBag.Message");
</script>
}

You need to pass ViewBag.alert as string to alert() function. Currently you are assign string to ViewBag.alert
Use
<script>
alert('#ViewBag.alert');
</script>

You need to add a message to the ViewBag in your controller.
public ActionResult Index() {
ViewBag.Message = "Plan Already Exists";
return View();
}
And then in your view, add a bit of script:
<% if (!string.IsNullOrEmpty(ViewBag.Message)) { %>
<script type="text/javascript">
alert('<%=ViewBag.Message%>');
</script>
<% } %>

You Can Use Like this:
Controller:
public ActionResult Index()
{
ViewBag.msg = "View Bag Value";
return View();
}
View:
if (!string.IsNullOrEmpty(ViewBag.msg))
{
<script type="text/javascript">alert('#ViewBag.msg');</script>
}

Related

Section not defined In Index.cshtml in asp.net mvc?

I define the section in Index. cshtml but when I run the application then generate an error section is not defined
I create the same another project, then define the simple method in Index. cshtml then run my application but my current project popup not be displayed??
another project
_layout.cshtml
<div class="container body-content">
#RenderBody()
#RenderSection("simpelmessage")
<footer>
<p>WebApi Crud Oeperation using Entity Framework In Mvc</p>
</footer>
</div>
Index.cshtml
#section simpelmessage{
<h1>simple message</h1>
}
that is work in another project
but my current working project my popup should not be displayed??
I m performing crud operation using api
_layout.cshtml
<div class="container body-content">
#RenderBody()
#RenderSection("alertpopup")
<footer>
<p>WebApi Crud Oeperation using Entity Framework In Mvc</p>
</footer>
</div>
Index.cshtml
#section alertpopup
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(function () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
});
</script>
}
HomeController.cs
public ActionResult Index()
{
IEnumerable<studentmvcmodel> stdlist;
HttpResponseMessage response = globalvariable.webapiclient.GetAsync("studlogins").Result;
stdlist = response.Content.ReadAsAsync<IEnumerable<studentmvcmodel>>().Result;
ViewBag.message = "record is inserted";
return View(stdlist);
}
public ActionResult create()
{
return View();
}
[HttpPost]
public ActionResult create(studentmvcmodel stud)
{
var username = stud.username;
var passs = stud.password;
if (username != null && passs != null)
{
HttpResponseMessage response = globalvariable.webapiclient.PostAsJsonAsync("studlogins", stud).Result;
ViewBag.message = "data inserted successfully";
return RedirectToAction("Index");
}
else
{
ViewBag.message = "please all the data fillup carefully";
return View("create");
}
}
My record should be created, but I want to popup message when submits the record?? but give the error section is not defined??
What I am trying I went to when I press the submit button, then a popup should be displayed but popup not display?
I hope my question is understood?
I m going to the browser and then ctrl+U then show the popup function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(function popup()
{
var successmessage = 'record is inserted';
if (successmessage != '')
{
//alertify.success(successmessage);
alert('record is inserted');
}
});
popup();
</script>
To avoid section is not defined error you need to call RenderSection as below.
#RenderSection("alertpopup", false)
And to make the pop up work, you have defined your javascript function but you are not calling you function anywhere. you can do this instead.
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript"></script>
<script>
function popup () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
}
popup();
</script>
If you return View("create"), so you should render your section in Create.cshtml Or define this #RenderSection("alertpopup", false) in your Layout
Rendering sections take two parameters; a string and a boolean as such:
#RenderSection(string name, bool required)
The name parameter is name of the section to render and required indicates that the section must always be rendered. If the section may not be rendered in some views or sometime, you should set required to false like below.
#RenderSection("alertpopup", false)
I'm also not sure when you want your popup to display because it is not called in your code. If for whatever reason you'll want it to be called when your documents loads, you should change your code to this
#section alertpopup
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(doucument).ready(function () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
});
</script>
}

Javascript function found in Index view, but not other views

I am using ASP.NET MVC 4 to develop a web application. I have an external javascript file which contains a method initializeLocation(). If I reference the file in the Index view of my Home controller it works fine. But when I try to reference the JS file in another view, and call the method in the body onLoad, then I get the following error:
Uncaught ReferenceError: initializeLocation is not defined
Here is the code of my view:
#{
ViewBag.Title = "Online Users";
}
<html>
<head>
<title>Online Users</title>
</head>
<body onload="initializeLocation()">
<h2>Online Users</h2>
<div id="wrapper">
<div id="upperPanel">
<div>
<ul id="onlineUsers" itemid="#HttpContext.Current.User.Identity.Name">
</ul>
</div>
<div id="friends">
</div>
</div>
<div id="bottomPanel">
<input id="submitLocation" type="submit" value="Share Location" style="margin-left: 10px;" /><br />
</div>
</div>​​​​​​​​​​​​​
<label id="locLabel"></label>
<div id="map" style="width: 100%; height: 600px"></div>
<script>
var Pusher_APP_KEY = 'b5ee1a1486b7f0cec06f';
</script>
<script src="http://js.pusher.com/1.12/pusher.min.js"></script>
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsjVTOfgW39medqXn6cmOTfVyyxIX3Nl8&sensor=true"> </script>
<script type="text/javascript">
//postURL is used in locationFinder.js to set the URL of POST requests
//It is declared here to be able to use a separate java file instead of embedding it
var postURL = '#Url.Action("Index", "Home")';
</script>
<script type="text/javascript" src="~/Scripts/locationFinder.js">
</script>
</body>
</html>
And here is my controller code:
namespace LBSPrototype1.Controllers
{
public class HomeController : Controller
{
private static readonly PusherProvider Provider = new PusherProvider
(
ConfigurationManager.AppSettings["pusher_app_id"],
ConfigurationManager.AppSettings["pusher_key"],
ConfigurationManager.AppSettings["pusher_secret"]
);
public ActionResult Index(string latitude, string longitude, string username)
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//
// GET: /Home/OnlineUsers
[AllowAnonymous]
public ActionResult OnlineUsers()
{
return View();
}
//
// POST: /Home/OnlineUsers
[AllowAnonymous]
[HttpPost]
public ActionResult OnlineUsers(string latitude, string longitude, string username)
{
var now = DateTime.UtcNow;
var request = new ObjectPusherRequest(
"chat_channel",
"message_received",
new
{
lat = latitude,
lon = longitude,
user = username,
timestamp = now.ToShortDateString() + " " + now.ToShortTimeString()
});
Provider.Trigger(request);
return View();
}
}
}
I'm new to MVC and am still getting used to the concept of controllers and such, but can't see why the exact same code should work in one view and not the other.
Instead of
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="~/Scripts/locationFinder.js"></script>
Use
<script src="#Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/locationFinder.js")" ></script>
The problem is the url which is render on the page. use #Url.Content to render a url with its rool path reference. it will render correct url while in routing.

Inject/inserting the values directly on the view MVC 4

I am new to MVC, and have a MVC 4 web application and I retrieve a collection of items in the application start(static reference data). I want to display this collection of items when my view loads and loop through it creating links on view, I want to use javascript to inject this information. I found a post where they mention doing it in the view like this
<script type="text/javascript>
<%= Model.JavascriptToInsert %>
</script>
but I am looking for a working example of implementing this approach. Any guidance would be appreciated.
You should serialize your collection to json before you put it to your page.
Use ViewBag to show the data
Controller:
//Show data with ViewBag
public ActionResult Index()
{
ViewBag.DataList = SomeClass.SomeStaticList;
return View();
}
View:
<script type="text/javascript">
var list = <%=Json.Encode(ViewBag.DataList)%>;
for (var i = 0; i < list.length; i++) {
//do something with your data
}
</script>
Use strongly-typed view
Controller:
//Show data with ViewModel
public ActionResult Index()
{
var model = new TempProject.Models.SampleModel();
model.ListData = SomeClass.SomeStaticList;
return View(model);
}
View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<TempProject.Models.SampleModel>" %>
<script type="text/javascript">
var list = <%=Json.Encode(Model.ListData) %>;
for (var i = 0; i < list.length; i++) {
//do something with your data
}
</script>

JavascriptResult puts javascript to the page as a string?

Iam a newbie of .NET MVC. I was trying to run all return types of MVC but I couldnt do work javascriptResult. The below is in my controller:
public ActionResult DoSomething() {
string s = "alert('Hello world!');";
return JavaScript(s);
}
This is in my view
#Ajax.ActionLink("click", "DoSomething", new AjaxOptions())
When I clicked the link, it puts "alert('Hello world!');" as a string and so not firing the alert. Whats wrong here ?
Seems that the documentation is "wrong" and the Controller.JavaScript action result is most likely only considered to return JavaScript include files (see also this thread):
Controller
public ActionResult JavaScript()
{
string s = "alert('Hello world!');";
return JavaScript(s);
}
View
<script type="text/javascript" src="~/Controller/JavaScript"></script>
If you want to return inline JavaScript you can use Controller.Content as your action result in combination with Html.RenderAction:
Controller
public ActionResult JavaScript()
{
string s = "alert('Hello world!');";
return Content(s);
}
View
<script type="text/javascript">
#{ Html.RenderAction("JavaScript", "Controller"); }
</script>

Generate javascript file on the fly in asp.net mvc

Friends,
I am trying to use DyGraph in my application. Please look at the code below -
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
<title>crosshairs</title>
<script type="text/javascript" src="dygraph-combined.js"></script>
<script type="text/javascript" src="data.js"></script>
</head>
The code uses data.js file containing function to get some static data.
I want data.js to be generated using a controller method so that it will generate data using database.
Can anybody help me out to resolve this issue.
Thanks for sharing your valuable time.
You could define a controller action:
public ActionResult Data()
{
// Obviously this will be dynamically generated
var data = "alert('Hello World');";
return JavaScript(data);
}
and then:
<script type="text/javascript" src="<%= Url.Action("Data", "SomeController") %>"></script>
If you have some complex script that you don't want to generate in the controller you could follow the standard MVC pattern by defining a view model:
public class MyViewModel
{
... put required properties
}
a controller action which would populate this view model and pass it to the view:
public ActionResult Data()
{
MyViewModel model = ...
Response.ContentType = "application/javascript";
return PartialView(model);
}
and finally a view which in this case will be the javascript representation of the view model (~/Views/SomeController/Data.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MyViewModel>" %>
alert(<%= new JavaScriptSerializer().Serialize(Model.Name) %>);
Full Disclosure
This answer is copy/pasted from another question:
Dynamically generated Javascript, CSS in ASP.NET MVC
This answer is similar to other answers here.
This answer uses cshtml pages rather than ascx controls.
This answer offers a View-Only solution rather than a Controller-Only solution.
I don't think my answer is 'better' but I think it might be easier for some.
Dynamic CSS in a CSHTML File
I use CSS comments /* */ to comment out a new <style> tag and then I return; before the closing style tag:
/*<style type="text/css">/* */
CSS GOES HERE
#{return;}</style>
Dynamic JS in a CSHTML File
I use JavaScript comments // to comment out a new <script> tag and then I return; before the closing script tag:
//<script type="text/javascript">
JAVASCRIPT GOES HERE
#{return;}</script>
MyDynamicCss.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
}
/*<style type="text/css">/* */
#foreach (var field in fieldList) {<text>
input[name="#field"]
, select[name="#field"]
{
background-color: #bbb;
color: #6f6f6f;
}
</text>}
#{return;}</style>
MyDynamicJavsScript.cshtml
#{
var fieldList = new List<string>();
fieldList.Add("field1");
fieldList.Add("field2");
fieldArray = string.Join(",", fieldList);
}
//<script type="text/javascript">
$(document).ready(function () {
var fieldList = "#Html.Raw(fieldArray)";
var fieldArray = fieldList.split(',');
var arrayLength = fieldArray.length;
var selector = '';
for (var i = 0; i < arrayLength; i++) {
var field = fieldArray[i];
selector += (selector == '' ? '' : ',')
+ 'input[name="' + field + '"]'
+ ',select[name="' + field + '"]';
}
$(selector).attr('disabled', 'disabled');
$(selector).addClass('disabled');
});
#{return;}</script>
No Controller Required (using Views/Shared)
I put both of my dynamic scripts into Views/Shared/ and I can easily embed them into any existing page (or in _Layout.cshtml) using the following code:
<style type="text/css">#Html.Partial("MyDynamicCss")</style>
<script type="text/javascript">#Html.Partial("MyDynamicJavaScript")</script>
Using a Controller (optional)
If you prefer you may create a controller e.g.
<link rel="stylesheet" type="text/css" href="#Url.Action("MyDynamicCss", "MyDynamicCode")">
<script type="text/javascript" src="#Url.Action("MyDynamicJavaScript", "MyDynamicCode")"></script>
Here's what the controller might look like
MyDynamicCodeController.cs (optional)
[HttpGet]
public ActionResult MyDynamicCss()
{
Response.ContentType = "text/css";
return View();
}
[HttpGet]
public ActionResult MyDynamicJavaScript()
{
Response.ContentType = "application/javascript";
return View();
}
Notes
The controller version is not tested. I just typed that off the top of my head.
After re-reading my answer, it occurs to me it might be just as easy to comment out the closing tags rather than use the cshtml #{return;}, but I haven't tried it. I imagine it's a matter of preference.
Concerning my entire answer, if you find any syntax errors or improvements please let me know.

Categories

Resources