This is my razor code which throws error:
#section script
{
<script type="text/javascript">
$(document).ready(function () {
#if (TempData["Message"] != null)
{
showNotification("'" + TempData["Message"].ToString() + "'");
}
});
</script>
}
It says showNotification doesn't exist. It thinks this is a C# code where it's a javascript function. Could anybody please let me know how do I fix this error? Thanks!
Throw a text tag around it, since the compiler thinks your JavaScript is Razor syntax. When you do this, you will need to add a # to the TempData call.
#section script
{
<script type="text/javascript">
$(document).ready(function () {
#if (TempData["Message"] != null)
{
<text>showNotification('#TempData["Message"].ToString()');</text>
}
});
</script>
}
In addition to #Martin's answer, you can also put #: in front of the showNotification call. The #: syntax tells Razor to treat that single line as HTML, where the tells Razor to treat anything within the text tag as HTML (useful for multi line, where #: is good for single line).
Related
I am getting the error below but I have it defined on the Layout page below. I changed the #(IsSectionDefined to #if(IsSectionDefined because I need to write null in the else statement. Why would this be an issue?
The following sections have been defined but have not been rendered for the layout page "~/Areas/Directors/Views/Shared/_MembersFormLayout.cshtml": "FormCallback".
Layout.cshtml
<form data-bind="form:{ id: #Model.FormId, callback: #if (IsSectionDefined("FormCallback")){RenderSection("FormCallback", false);}else {#(Html.Raw("null"))}}">
Page.cshtml
#section FormCallback{members.event.updateImage}
I was able to fix it with his helper function found at Is there a way to make a #section optional with the asp.net mvc Razor ViewEngine?
.
<form class="clearfix" action="#Request.RawUrl" data-bind="form:{ id: #Model.FormId, callback: #this.RenderSection("FormCallback", #<text>null</text>)}">
public HelperResult RenderSection(string name, Func<dynamic, HelperResult> defaultContents)
{
if (IsSectionDefined(name))
{
return RenderSection(name);
}
return defaultContents(null);
}
Here I have ViewBag in a controller which contains text i.e ViewBag.Msg = "No Sprint".
And I am trying to use ViewBag.Msg in Jquery to display modal.
Now, the problem is that the script is script never gets executed.
Below is my jQuery.
<script>
$(document).ready(function () {
debugger;
if (#ViewBag.Msg != null)
{
$("#myModal").modal();
}
});
</script>
Any help will be highly appreciated. Thank You.
You need to use quotation marks for the view bag, as it will appear as a literal string.
If your debugger is not hitting at all, then you have another issue, post your full code. (your .cshtml file and layout)
<script>
$(document).ready(function () {
debugger;
if ('#ViewBag.Msg' != null)
{
$("#myModal").modal();
}
});
</script>
Please use the below code.
<script>
$(document).ready(function () {
debugger;
var msg='#ViewBag.Msg';
if (msg !== '')
{
$("#myModal").modal();
}
});
</script>
Is it possible to run jQuery from a MVC C# controller?
if (ModelState.IsValid){
//lots of C# asp.net code here
jqueryFunctionName();
}
It's important that there is a check somehow before the jQuery runs
Perhaps i can do it straight from jQuery itself, but i'm not sure how to check it?
The idea is Form -> Submit -> SOMETHING checks if valid -> if yes then wait graphic -> 2 seconds pauze -> redirect to "thanks.cshtml"
In your controller's action:
var vm = new YourViewModelTypeWithPropertyIsValid();
vm.IsValid = ModelState.IsValid;
return View(vm);
In your view:
#model YourViewModelTypeWithPropertyIsValid
<script type="text/javascript">
var isModelValid = #Model.IsValid ? 'true' : 'false';
$( document ).ready(function() {
// Any JS code here
// ...
if (isModelValid) {
setTimeout(
function () {
location.assign('/redirect_path_after_2s_delay');
},
2000);
);
}
});
<script>
I prefer typed views.
If you use untyped views, use the code below.
In your controller's action:
ViewData["IsModelValid"] = ModelState.IsValid ? "true" : "false";
return View();
In your view:
<script type="text/javascript">
var isModelValid = #ViewData["IsModelValid"];
$( document ).ready(function() {
// Any JS code here
// ...
if (isModelValid) {
// See the code above.
}
});
<script>
If the code runs in the view then you can try something like this.
is a special asp tag.
If the should indeed run in controller, than it is not possible to run JS code there.
if (ModelState.IsValid){
//lots of C# asp.net code here
<text>
<script>
jqueryFunctionName();
</script>
</text>
}
I am trying to write the following javascript in Razor (MVC4).
(The Script tags are there)
var isPaid = true;
in the view I use the Model to get the value:
var isPaid = #Model.Paid;
<text>
var proceed = #Model.Paid;
</text>
var proceed = #Html.Raw(Model.Paid + ";")
Most of the time Resharper complains
You could try it this way:
<script type="text/javascript">
var isPaid = false; // This is JavaScript.
// The if statement is C#, hence the #.
#if (Model.Paid)
{
#:isPaid = true; // Set the JS variable to true.
}
// Below is JavaScript code again.
alert(isPaid);
</script>
Text after the #: nugget will be interpreted as as JavaScript. It is a bit of a hassle for booleans, a string property for example is a lot easier:
<script type="text/javascript">
var userName = '#Model.UserName';
</script>
You can't combine JavaScript inside HTML code and you need to put quotes & angle-brackets around the value so that it is considered as a string.
The problem seems to be this and more..:
var isPaid = #Model.Paid;
<text>
var proceed = #Model.Paid;
</text>
A proposed solution would be:
Normal JavaScript code should resides within a script tag, for example:
<script type="text/javascript">
var isPaid = '<%: #Model.Paid %>';
</script>
I would like to pass a parameter to the jQuery document.ready() function from my View:
$(document).ready(function (parameter){
$('select[name=Product]').val(parameter);
});
How can I fire the event from my View and pass the parameter? I use Razor as View engine.
Thanks
You can't. The document.ready function doesn't take parameters. You could for example define this parameter as a global variable in your view:
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
</script>
and then in your separate javascript file use this global variable:
$(function() {
$('select[name=Product]').val(model.SomeProperty);
});
To avoid using global variables, you can define a closure and then returning this function to ready():
function start(parameter)
{
return function()
{
/*...use parameter */
alert('parameter: ' + parameter);
}
}
and then call ready():
$(document).ready(start('someValue'));
You can also define the start function in a external .js file and calling ready (for example) in your main html file.
Example:
external script.js:
function start(parameter)
{
return function()
{
/*...use parameter */
alert('parameter: ' + parameter);
}
}
html file:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script>
$(document).ready(start('someValue'));
</script>
</head>
<body>
</body>
</html>
Calling ready() in the latter file allows you to pass server parameters to your functions. Example (using PHP. In this case you must change the extension from html to php to this file):
$(document).ready(start('<?php echo $serverParameter; ?>'));
You can effectively accomplish this with a closure. That is, if you are calling something like $(document).ready(startup) then you can easily rewrite startup so that you can call it with a parameter, e.g. $(document).ready(startup(7)). Pablo gave an excellent underrated answer, and it is worth giving a more detailed example.
Example
Here is a page which displays an alert, invoked by $(document).ready(), that calculates 6*9:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function startup() {
alert('6 * 9 = ' + 6 * 9);
}
</script>
</head>
<body>
Hello!
<script>
$(document).ready(startup);
</script>
</body>
</html>
Say you want to replace "9" with a variable parameter. The 4-step recipe to do this is:
Parameterize the function.
Wrap the function body in a closure. That is, return function() {...}.
Parameterize the body.
Call the function with the parameter.
Applying this to the above code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function startup(x) { // Step 1 - Parameterize the function
return function() { // Step 2 - Put body in "return function() {...}"
alert('6 * '+x+' = ' + 6 * x); // Step 3 - Parameterize the body.
} // (closing brace for step 2)
}
</script>
</head>
<body>
Hello!
<script>
$(document).ready(startup(7)); // Step 4 - Call function with parameter.
</script>
</body>
</html>
This displays the alert "6 * 7 = 42".
What's Happening?
$(document).ready() takes as its parameter a function. This is why it is called in the first version above with just startup as the parameter. In contrast if you called it with startup() you wouldn't be passing in the startup function anymore, you would be passing in the return value of startup.
Since $(document).ready() takes a function as its parameter, that's what we give it: startup is transformed in the second version above into a function that returns a function, which has the parameter x set to the value we pass it initially. That is, startup(7) returns a function to $(document).ready() that has the value of x set to 7.
OP's Question
To specifically apply this to the OP's question, rewrite that call as
$(document).ready((function(x) { return function() {
$('select[name=Product]').val(x);
}})('name'));
where 'name' can be any other value that gets substituted for x. No need for global variables.
More information: JavaScript closures.
You can simply echo your parameter value into the Javascript code if its inline in your view.
$(document).ready(function (){
$('select[name=Product]').val('#ViewBag.Parameter');
});