Calling JavaScript function in MVC 5 Razor view - javascript

I have seen in another post that you can call a JavaScript function in your razor code like so:
#:FunctionName()
For me though this only outputs the actual words FunctionName()
Here is my view:
#model PriceCompare.Models.QuoteModel
#{
ViewBag.Title = "Quote";
}
<h2>Quote</h2>
#if (#Model.clarify == true)
{
// do drop down loic
#:ShowClarify();
}
else
{
// fill quote
#:ShowQuote();
}
<div class="clarify">
You can see the clarify div
</div>
<div class="quote">
You can see the quote div
</div>
#section head {
<script type="text/javascript">
$(document).ready(
function ShowQuote() {
$(".quote").show();
},
function ShowClarify() {
$(".clarify").show();
}
);
</script>
}
Is it because I have nested it in an `#if'? Anyway around this?

You need to put your javascript in a <script> tag, and you need to call the functions within their scope:
<script type="text/javascript">
$(document).ready(
function ShowQuote() {
$(".quote").show();
},
function ShowClarify() {
$(".clarify").show();
}
#if (#Model.clarify == true)
{
// do drop down loic
ShowClarify();
}
else
{
// fill quote
ShowQuote();
}
);
</script>

If you are passing any parameter to the JavaScript function, it must be enclosed with quotes ('').
foreach (var item in files)
{
<script type="text/javascript">
Attachment(**'#item.FileName'**, **'#item.Size'**);
</script>
}

Related

mvc view jquery javascript

How do I call a javascript function from within razor markup in a cshtml view? Basically I want to do something like this (which doesnt work):
Javascript file being included on the page has a method like this:
<script type="text/javascript">
function doesThisWork() {
return true;
}
</script>
View has code block similar to this:
<div>
#if(doesThisWork()) {
<span> this DOES work!!! </span>
}
else
{
<span> this does NOT work!!! </span>
}
</div>
You cannot call the javascript function on the server side but it can be achieved as below code.
Html:
//Declare a div where you want display html
<div id="bindHtml"></div>
Script:
<script type="text/javascript">
//On pageload call function and display Html based on your function return.
$(document).ready(function(){
let htmlContent = "";
if(doesThisWork()){
htmlContent = "<span> this DOES work!!! </span>";
}else{
htmlContent = "<span> this does NOT work!!! </span>";
}
//Bind Html to declared div in the Html
$("#bindHtml").append(htmlContent);
});
function doesThisWork() {
return true;
}
</script>

Unable to execute scripts depending on Thymeleaf variables <script th:inline="javascript">

I have 2 simple scripts and 2 Thymeleaf variables, I want one script to be executed if thymeleaf variable is true, then again if other variable is true - related script to be executed and so on. But I get the following result - if one variable is true and script executed then second script won't be execudet even if second variable is true. So shortly, only one of scripts is executed, but need both (in sequence, not the same time). Here is the code:
<script th:inline="javascript">
var flag = [[${invalidInput}]]; //Thymleaf variable
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<script th:inline="javascript">
var flag = [[${exists}]];
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<!-- MODAL -->
<div class="form-popup" id="myForm">
<form id="registration" th:action="#{/registrate}" th:object="${newUser}" method="post" class="form-container">
<h1>Registration</h1>
<div class="alert" th:if="${exists}">
User already exists! Please try again.
</div>
<div class="invalidInput" th:if="${invalidInput}">
Username or password too short.
</div>
************************************************************
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
#PostMapping("/registrate")
public String login (#ModelAttribute(value = "newUser") User newUser, BindingResult bindingResult, Model model) {
userValidator.validate(newUser, bindingResult);
if(usrService.isUserPresent(newUser.getUsername())){
model.addAttribute("exists",true);
return "login";
}
else if(bindingResult.hasErrors()){
model.addAttribute("invalidInput",true);
return "login";
}
I don't think you can set the window.onload variable twice... one will simply overwrite the other. You can either combine your logic like this:
<script th:inline="javascript">
var invalidInput = [[${invalidInput}]]; //Thymleaf variable
var exists = [[${exists}]];
window.onload = function() {
if(invalidInput) {
openForm();
} else if (exists) {
openForm();
}
};
</script>
Or alternatively you could use something like jQuery, which has this functionality built in for you.
https://api.jquery.com/ready/
When multiple functions are added via successive calls to this method,
they run when the DOM is ready in the order in which they are added.

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>
}

How to use model attribute of a JSP into javascript?

Controller:
List<SampleModel> data = service.getdata();
model.addAttribute("modeldata",data);
return "jsp";
Is there a way to easily access/use the model attribute of a jsp in a javascript function? I tried accessing it in a loop but there's no result.
Sample:
<script type="text/javascript">
$(document).ready(function() {
sampleFunction();
});
sampleFunction() {
for (i=0;i<=10;i++) {
console.log(${modeldata[i].sampledatapath});
}
}
</script>
Thanks!
You can use following:
<script type="text/javascript">
$(document).ready(function() {
sampleFunction();
});
function sampleFunction(){
<c:forEach var="model" items="${modeldata}">
console.log("${model.sampledatapath}");
</c:forEach>
}
</script>

call javascript function when the view is loaded in mvc

I am trying to call a js function inside my view :
#model DomainClass.Group
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
<script language="javascript" type="text/javascript">
document.read = function myFunction() {
if (ViewBag.State == "error") {
if (confirm("معیار مورد نظر دارای زیر مجموعه های مرتبط است. آیا تمایل به ویرایش دارید ؟")) { } else {
history.back();
}
}
}
</script>
}
}
#using (Html.BeginForm())
{
//my code
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
As you can see the my function name is myfunction and it depends on viewbag value ,but never it is't called by browser!!!
Should i add extra code to my view ?
Any ideas will be appreciated .
Best regards
Your Script is never executed because it won't be rendered to the page. So i moved it out of the server tags and into the HTML markup. Only filling in the parameter you need. But then you have a second problem. You sign the function to a variable on the window. No matter the name of the function on the right side it will be named the one on the left side. In fact, the right side shouldn't have a name al togheter. Then the third and final problem is, you don't call the function anywhere. Since i see that you included jquery validate i presume you also included jQuery and made use of their document ready function.
I've included an update of your function. There is some more room for optimalisation but it didn't include them to make it clear where your mistakes where.
#model DomainClass.Group
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script language="javascript" type="text/javascript">
//use window instead of document
window.myFunction = function () {
//Try setting the boolean this way
var x = #(ViewBag.State == "error" ? "true" : "false");
if (confirm("معیار مورد نظر دارای زیر مجموعه های مرتبط است. آیا تمایل به ویرایش دارید ؟")) {
}
else {
history.back();
}
}
$(function () {
window.myFunction();
});
</script>
#using (Html.BeginForm())
{
//my code
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

Categories

Resources