How to get viewbag data in jquery? - javascript

Hi I am developing web application in mvc5. I have login form with username and password fields as below.
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid",
#class = "form-control validate[requiredInLogin] text-input "})
#Html.Password("txtPassword", null, new { #maxlength = "15", id =
"txtPassword", #class = "form-control validate[requiredOutLogin] text-input" })
<input type="submit" class="btn btn-primary btnLogin red"
value="SIGN IN" name="submit" />
}
I have below action method,
[HttpPost]
public ActionResult ClickAction()
{
//Some logic
//When 3 unsuccessful attempts made to login then i set
//ViewBag.captcha = true;
return View();
}
I will make 3 unsuccessful attempts to login then i will set ViewBag.captcha to true. Once i set ViewBag.captcha to true i want to access the ViewBag.captcha value in View and i want to display captcha. May i know how can i access Viewbag value in view? any help would be appreciated. Thanks,
Meanwhile i tried below options,
#{
var message = ViewBag.captcha;
}
Then in JS
var message = '#message';
if (message)
{
alert(message);
}
Below is my login view.
<html>
<head></head>
<body>
<div id="formID">
#*<form id="formID">*#
<div class="loginContainer">
<div class="loginContentArea">
<div class="loginLogo"><img src="~/images/c3card.png" alt="C3 Card" align="middle" /></div>
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
<div class="loginUsernamePassword">
<i class="fa fa-user"></i>
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid", #class = "form-control validate[requiredInLogin] text-input ", placeholder = "Username", autocomplete = "off" })
</div>
<div class="loginUsernamePassword">
<i class="fa fa-lock"></i>
#Html.Password("txtPassword", null, new { #maxlength = "15", id = "txtPassword", #class = "form-control validate[requiredOutLogin] text-input", placeholder = "Password", autocomplete = "off", Style = "background:#FFFFFF;" })
</div>
<div class="errormessage">#TempData["Message"]</div>
<div class="captcha" id="captcha">
<div class="g-recaptcha" data-badge="inline" data-sitekey=#System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>
<br />
</div>
<div class="loginButton">
<input type="submit" class="btn btn-primary btnLogin red" value="SIGN IN" name="submit" />
</div>
<div class="loginLink">#Html.ActionLink("Forgot Your Password?", "Index", "ForgotPassword")#**#</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('input[type=password]').each(function () {
$(this).attr('data-background-color', $(this).css('background-color'));
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
$(this).focus(function () {
$(this).attr('type', 'password');
$(this).css('background-color', $(this).attr('data-background-color'));
});
$(this).blur(function () {
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
});
});
});
jQuery(document).ready(function () {
#{ var message = ViewBag.captcha; }
alert(message);
if (message) { alert(message); }
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});
$("#myinput").rules("add", {
minlength: 2
});
</script>
</body>
</html>
This does not work for me.
May i know proper way to access viewbag value in the above scenario? Any help greatly appreciated. Thank you so much.

Since you are using Razor you could do this:
1. Get your ViewBag value to a variable
<script type="text/javascript">
var message = "#ViewBag.captcha";
</script>
You don't have to set it inside your document ready.
2.The variable is of type string however. In order to use it in a function you will have to do something like that:
If(message.toLowerCase() == "true")
in order to get the desired effect.
To convert it to boolean you could use something like that
message = message.toLowerCase() === "true"
Hope it helps

You can initialize a ViewBag value like this:
ViewBag.captcha = "true";
Then you can access it like this in a view:
var message = #ViewBag.captcha;
From here on you will be able to use message. What you essentially did was the following:
you initialize ViewBag.captcha (note that this part is commented out)
you put that into a variable called message
you try to get #message as a string, but you are not using the Javascript value calculated

Can you change the message variable like below in JS and then try
jQuery(document).ready(function () {
var message = '#ViewBag.captcha'; //change it here
if (message)
{
alert(message);
}
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});

Related

Meteor template won't reference event or method

In meteor.js, I've having trouble connecting the HTML and the JS. There's no reaction on the button click, and I don't see why not. Therefore the meteor method in server isn't called, and no email is sent.
HTML:
<template name='confirmation'>
<div class = "container" >
<form role = "form" id = "email-form">
<div class = "form-group">
<label for="inputEmail">Email address</label>
<input type= "email" class = "form-control" id = "inputEmail" placeholder = "Enter email">
</div>
<button type = "submit" class = "btn btn-primary"> Send mail</button>
</form>
</div>
</template>
This code runs on the client:
Template.confirmation.events({
'submit #confirmation-form': function (e,t) {
e.preventDefault();
var toAddr=t.find('#inputEmail').value;
var subject = ("Booked");
var body = ("Thanks for booking")
Meteor.call('sendEmail', toAddr, subj, text)
}
})
This code runs on the server:
if (Meteor.isServer){
Meteor.startup(function(){
process.env.MAIL_URL = "mailgun"
Accounts.config({
sendVerificationEmail: true
})
})
Meteor.methods({
'sendEmail': function(toAddr,subj,text){
this.unblock();
Email.Send({
from: "booking#timesharewebapp.com",
to:Meteor.toAddr,
subject : subj,
text: text
})
}
})
}
The problem is that nothing will react when I press the button. Nothing comes up in the console, or in the cmd prompt. I don't know if it's the way I'm calling my events, or if it's the email function.
You are using the wrong selector on the event. Try the below code.
Template.confirmation.events({
'submit #email-form': function (e,t) {
e.preventDefault();
var toAddr=t.find('#inputEmail').value;
var subject = ("Booked");
var body = ("Thanks for booking")
Meteor.call('sendEmail', toAddr, subj, text)
}
})

Verification in DropDownListFor ASP.NET

i have one element span where i can write name of courier, during the writing it's searching couriers from database. I have also one element dropDownListFor where i can chose one courier. My problem is that, when i wrote a name which not exist in my datadase i dont have any information about that. I wanted to hide submit button if the DropDownListFor is empty - the name from span is incorrect, but it doesn'twork. How can i do this?
I have partialview like this:
div class="col-md-12">
<div class="col-md-offset-4 text-center">
<input type="text" oninput="Finder(this, '#CourierId'), check()" class="form-control" value="#Model.CourierName" id="courier-finder" placeholder="Select courier"/>
#Html.DropDownListFor(model => model.CourierId, (List<SelectListItem>)ViewBag.Couriers, new { #class = "form-control", onchange = "RefreshInput(this, '#courier-finder')" })
#Html.HiddenFor(model => model.TaskId)
</div>
<script>
function check() {
if (document.getElementById("CourierId")== "-1") {
$("#buttonDeleteMODALAssign").hide();
}
}
Try :
function check() {
if ($("#CourierId").val()== "-1") {
$("#buttonDeleteMODALAssign").hide();
}
}
OR
function check() {
if (document.getElementById("CourierId").value== "-1") {
document.getElementById("buttonDeleteMODALAssign").style.display = 'none';
}
}

ASP.NET when form onsubmit called DOM elements disappear

I have simple Html.BeginForm with some data, and i want to check some condition using onsubmit() javascript function when user clicked "submit" button, before form will be send. And when this condition is false, I want to stop reloading page, just don't send my form to POST method. This is working fine, bit I met a problem, because DOM elements which I create in onsubmit() method disappear:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", **onsubmit=" return registerValidation()"**}))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #id = "emailVal"})
#Html.ValidationMessageFor(m => m.Email,"", new { #class = "validation-error-white", #id="emailValidation"})
<input type="submit" class="btn btn-warning btn-block add-item-button-text" value="Zarejestruj" />
}
<script type="text/javascript">
function registerValidation() {
var validForm = validateRegisterForm(email, login);
if (!validForm) {
$('#emailValidation').append('Those email already exists! Take another one');
return false;
}
return true;
}
</script>
So when I want to return false, and do not send form, text that I append to validation-div that says what's wrong disappear - it's not what I want to achieve, because it's very small period of time and user cannot even notice that!
You manually trigger the button click event. Make sure type is button.
You do not need **onsubmit=" return registerValidation()"**
<input id="btnSubmit" type="button" ... />
<script type="text/javascript">
$(function () {
// Trigger btnSubmit button's click event, when enter key is pressed.
// If you do not want that feature, you can ignore this.
$("form").keydown(function (event) {
if (event.keyCode === 13) {
$("#btnSubmit").click();
return false;
}
});
$("#btnSubmit").click(function () {
// Do something, then submit the form
$("form").submit();
});
});
</script>

document.getelementbyid not recognizing razor element

In my index.cshtml file I have a razor element (#Html.EditorFor) that's a text box. Javascript isn't recognizing the element. If I change the element type to a non-razor syntax then javascript can see it. Am I missing some syntax here.
index.cshtml
<div class="jumbotron">
<h1>my application</h1>
#using (Html.BeginForm("Results", "Home", FormMethod.Post))
{
<div class="form-group">
//javascript can't see mainpagequery
#Html.EditorFor(model => model.SearchQuery, new { htmlAttributes = new { #class = "form-control", id = "mainpagequery" }})
#Html.ValidationMessageFor(model => model.SearchQuery, "", new { #class = "text-danger" })
//javascript can see mainpagequery in the non razor element here
<input type="text" class="form-control" placeholder="Search" id="mainpagequery">
</div>
<button type="submit" class="btn btn-default">Search</button>
}
Here is my javascript. If I use razor then 'mainpagequery' is underlines because it can't see it, if I use html then it's fine. I know I'm hitting my javascript because I see the alert message pop up.
$(document).ready(function () {
console.log("ready!");
alert("mainpage autocomplete function entered");
var input = document.getElementById('mainpagequery');
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var mainpagequery = new window.google.maps.places.Autocomplete(input, options);
});
In case of #Html.EditorFor your id get overriden to model's property name.
If you find element using f12 you will find it as follows. (Notice id "SearchQuery124" I just renamed it to something)
So in your case in make change like
$(document).ready(function () {
console.log("ready!");
alert("mainpage autocomplete function entered");
var input = document.getElementById('SearchQuery').value;
console.log(input);
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var mainpagequery = new window.google.maps.places.Autocomplete(input, options);
});
Try this
Instead of #Html.EditorFor use
#Html.TextBoxFor(model => model.SearchQuery, new { #class = "form-control" , id = "mainpagequery"})

Javascript enable/disable button not working as expected

This is my logon view:
#model SuburbanCustPortal.Models.LogOnModel
#{
ViewBag.Title = "Log On";
}
<h2>Log On</h2>
<p>
Please enter your user name and password. #Html.ActionLink("Register", "Register") if you don't have an account.
</p>
<p>
If only you wish to make a payment on your account and do not want to create a website login, #Html.ActionLink("click here", "RedirectToPaymentPage", "Account").
</p>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field focus">
#Html.TextBoxFor(m => m.UserName, new { #class = "GenericTextBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<p>
<button name="btn" value="Log On" onclick="disableButton()" disabled="disabled">Log On</button>
</p>
<p>
If you need to retrieve your username #Html.ActionLink("click here.", "ForgotUsername", "Account")<br/>
If you need to reset your password #Html.ActionLink("click here.", "ForgotPassword", "Account")
</p>
</fieldset>
</div>
}
This is my widget.js:
function enableLogonButton() {
if ($('#UserName').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
$('#btn').removeAttr('disabled');
}
function logonDisableSubmitButtons(clickedButton) {
$("input[type='button']").each(function() {
if (this.name != clickedButton)
$(this).attr("disabled", "disabled");
else {
//hiding the actually clicked button
$(this).hide();
//Creating dummy button to same like clicked button
$(this).after('<input type="button" disabled="disabled" value="' + $(this).val() + '" class="' + $(this).attr('class') + '" />');
}
});
}
function disableButton() {
$('#btn').click(function (e) {
$(this).attr('disabled', 'disabled');
});
}
I'm not having the button enabled no matter what I do.
What I am wanting is two things:
When the user has something in the logon and username, enable the submit button.
When they click submit, the button is disabled so they cannot click it twice.
I'm not having luck with either.
I have made the changes suggested below but the button is still not being enabled once I have entered something in the fields
** FURTHER TESTING**
I added the alerts() as suggested as such:
function enableLogonButton() {
alert("start");
if ($('#UserName').val() == "") {
alert("username");
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
alert("password");
$('#btn').attr('disabled', 'disabled');
return;
}
alert("enabled");
$('#btn').removeAttr('disabled');
}
Not one of them are firing off. At least, I'm getting no prompt.
So, then I changed the call to this to make sure it was even seeing the JScript:
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButtonX()" })
And I get this message:
Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
So, I believe it is seeing the JScript.
I then added this:
<script>
function myFunction() {
alert("hit!");
}
</script>
And changed this:
<button name="btn" value="Log On" onclick="myFunction()" disabled="disabled">Log On</button>
And my "hit" worked. So, I believe the onclick is working also.
disabled is a boolean property, not an attribute.
To set:
$('#btn').attr('disabled', 'disabled');
To clear:
$('#btn').removeAttr('disabled')
Unless I'm not reading your question close enough (which, admittedly, could be the case since it is after 5 here...time for beer) or you have a typo in your question, I think your error message gives you everything you need to debug this.
Here is your message: Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
Here is your function name: enableLogonButton
So, according to the error message, you are calling the function enableLogonButtonX() but your function is named enableLogonButton. Change to this:
#Html.PasswordFor(m => m.Password, new {
#class = "GenericPasswordBox",
onkeyup = "enableLogonButton()" })
Instead of changing the value of disable attribute remove it completely from element.
i.e. Replace this
$('#btn').attr('disabled', false);
With
$('#btn').removeAttr('disabled');

Categories