I have been following this short and sweet tutorial : Integrating google recaptcha
I have made the relevant modifications to my view as shown here:
<div class="form-group" style="margin-left: 7%;">
#Html.Recaptcha("MyKeyGoesHere", CaptchaTheme.Dark)
#Html.ValidationMessage("ReCaptcha")
</div>
My controller looks like this:
[HttpPost]
[ValidateAntiForgeryToken()]
[CaptchaValidator]
public ActionResult SignUp(RegistrationSignUp model, bool captchaValid)
{
if (ModelState.IsValid) // Make sure all fields are field out.
{
}
return View(model);
}
But captchaValid is always false even though I have checked the check box? have I missed something? any help would be appreciated.
Try this;
var response = Request["g-recaptcha-response"];
if (response != null && ReCaptcha.IsValid(response))
{
//
}
I managed to get this working, by diving further into the complete documentation as shown here: Complete integration guide for Google ReCaptcha
Related
I have a controller with a create ActionResult which saves data in a webform.
When the information in saved in the form i would like to display a label saving the data was saved.
Is this possible to do?
Thanks
Ofcourse it is possible to do. Something along these lines should work fine. You can apply the same principles for an error message. The reason i put the if to check whether the view bag is null is because that bootstrap class will put an empty green block on the screen if its null
razor view
#if(ViewBag.Success != null){
<p class="alert alert-success">#ViewBag.Success</p>
}
mvc Post
[HttpPost]
public ActionResult ActionName(FormData fd){
//... save your form
ViewBag.Success = "You have successfully saved something."
Return View();
}
I'm developing a backend in MVC 5 for a client to update in their website. However I got across this error:
Error Image
This is the controller with the methods with the AntiForgeryToken
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
[System.web.Mvc.AuthorizeSectionccess(sectionname = "IT")]
public ActionResult Create()
{
return View();
}
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
[System.web.Mvc.AuthorizeSectionccess(sectionname = "IT")]
[System.web.Mvc.AuthorizePermitionAccess(PermissonType = "Add")]
[HttpPost]
public ActionResult Create(Welcome_conteudoPage model)
{
DB.Welcome_conteudoPage.Add(model);
DB.SaveChanges();
return Redirect("Index");
return View(model);
}
And this is the View
#using (Html.BeginForm("Create", "ConteudosPageController", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
#Html.TextAreaFor(model => model.ConteudoStandard)
</div>
<div>
<input type="submit" value="Inserir" class="btn btn-primary"/>
</div>
<div>
Texto:
#Html.DisplayFor(model => model.ConteudoStandard)
</div>
}
I'm using the AntiForgeryToken on both ends and still get that error. I know that there are thousands of questions like this but I've tried all of the proposed solutions for 3 days and without any result.
EDIT: I forgot to mention that the view is going to call the controller and model for a tinyMCE Editor
It might not be the answer, however, you may have misunderstood what the anti forgery token does and where to use it.
Firstly, when you use #Html.AntiforgeryToken in a view, it registers something in either the session or cookie (can't remember which).
The validate anti forgery token attribute looks for that token and matches it against the passed in token in the hidden field. If it doesn't match, then most likely the post request didn't come from your view.
The thing to note, is that this requires a body parameter on the request to send in the token. You wouldn't have this on requests that don't have a body. A Get request doesn't have a body, and therefore doesn't need the validateantiforgerytoken attribute on it.
I was researching about how to check if the cookies are enabled in a browser and i found a lot of answer, i even tested a few ones, but after that a friend of mine suggest me to use Modernizr for that.
I started to search about that and i found a lot of stuff related with CSS3 and HTML5, but i don't want that, i just wanna know if is it possible to check that cookies are enabled or not with Modernizr?
check this url, hope it's helpful :
https://github.com/Modernizr/Modernizr/commit/33f00fbbeb12e92bf24711ea386e722cce6f60cc
Below code is copied from http://sveinbjorn.org/cookiecheck.
function are_cookies_enabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
{
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
}
return (cookieEnabled);
}
A direct answer to the question is 'Yes!' and it is built in
Example code:
if (Modernizr.cookies == false) {
alert('Please enable cookies');
}
else {
// do something with cookies
}
You can also use the css class .cookies or .no-cookies to show/hide a panel telling the user they need cookies enabled.
.cookies #noCookies
{
display: none;
}
<div id='#noCookies'>
This site requires cookies! Please turn them on already!
</div>
(This .cookies class is added to <body> tag by Modernizr).
Note: If you are creating a custom build of Modernizr the cookies option is currently 'hidden' under the 'Non-core detects' section.
Another way with PHP
HTML/PHP:
<?php
session_start();
$_SESSION['cook'] = 1;
echo "<img src=\"cookcheck.php\">";
?>
PHP - cookcheck.php:
<?php
session_start();
if ($_SESSION['cook'] !== 1)
{ $image="/nocookmsg.png"; } # Cookies NOT Enabled
else { $image="/blank.png"; } # Cookies Enabled
$img=imageCreateFromPNG($image); # Create Image
header("Content-type: image/png"); # Send Header
imagePNG($image); # Send Image
?>
I've seen a lot of questions about this already, but I'm stumped! Please help!
I have a customvalidator. It's firing but it's not preventing postback. Please help me in doing so! I can see that console.log registers before the post. But, it posts back anyway. How do I prevent the postback?
I've tried adding a control to validate, and validate empty text equal to true. I also tried adding e.preventdefault, which did not work :(
How can I prevent the postback?
<script type="text/javascript">
//<![CDATA[
function validateWhyUnlikely(source, args) {
console.log(1);
args.isValid = false;
}
//]]>
<asp:TextBox ID="txtWhyUnlikely" runat="server" Rows="4" cols="20"
CssClass="surveyTextArea" />
<asp:CustomValidator runat="server" ID="cfvWhyUnlikley" ErrorMessage="Please provide a reason since you rated an item as unlikely to provide."
CssClass="surveyError surveySmallIndent" Display="Dynamic"
ClientValidationFunction="validateWhyUnlikely" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="smallSpecial" OnClick="btnSubmit_Click" />
jQuery(document).ready(function () {
jQuery('#<%= btnSubmit.ClientID %>').click(function (e) {
if (Page.IsValid == false) {
console.log(false);
e.preventDefault();
return false;
}
});
});
Everything looks ok althought I am not sure why you are attaching the Click function to your submit button. I would remove that and test it as it maybe be overriding the default behavior.
Also I think you need to capitalize the IsValid property:
args.IsValid = false;
I too faced this issue, I was trying to add a custom validator to a dropdownlist which had a selectedIndexChange event attached to it. After i gave incorrect value for dropdown, i was able to se ethe error message i gave in Custom Validator but immediately after it Postback was happening.
However on adding this property CausesValidation="true" to the dropdownlist control resolved my issue.
Postback wasn't happening on incorrect value after adding this property to my dropdown.
If it helps other people, I had a Validation group that I forgot to add the button to.
Make sure to add the button, the textbox and the validator to the same validation group for the postback to be prevented.
I experienced this problem as well.
What I did was, in the C# procedure that was called by the button, at the top I added
if (IsValid == false)
return;
I could not stop it performing the postback so this seemed to me like the only solution.
You are misssing ControlToValidate="txtWhyUnlikely"
Posting this as it might help someone that is getting the same weird behavior.
Initially I had the same issue as this post title. I checked all the suggestions here but my code seemed to be fine.
To fix this I replaced my cause validation control <asp:Button.. with a <button.. . Not sure why this is happening but happy it's working now.
hth
<button tags are missing the correct javascript code to validate.
<asp:Button does have the correct javascript rendered.
I've added this to any button tags:
btn.Attributes("onclick") = StringFmt("if(!Page_ClientValidate(''))return false;")
and that solved the post-back issue. No post-back occurs if the client-side detects an issue.
I solved this problem by creating a variable:
Boolean fieldIsValid = true;
and at the custom validating expression I would change the value if arguments weren't true:
if(args.IsValid == false)
{
fieldIsValid = false;
}
else
{
fieldIsValid = true;
}
Then, I also put that in the submit click method:
protected void submit_Click(object sender, EventArgs e)
{
if (fieldIsValid)
{
//submit my things
}
}
I have a show which displays a form with fields populated from a document. I'd like to change the values in the field and then save the updated document.
I'm having trouble finding a clear, concise example of how to do this.
Seriously, just finishing this example would work wonders for so many people (I'm going to leave a lot of stuff out to make this concise).
Install Couchapp
This is outside the scope of my question, but here are the instructions for completeness.
Create a couchapp
Again, this is kind outside the scope of my question. Here is a perfectly concise tutorial on how to create a couchapp.
Create a template
Create a folder in the root of your couchapp called templates. Within the templates folder create an HTML page called myname.html. Put the following in it.
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<form method='post' action='#'>
<fieldset>
Hello <input type='text' name='name' value='{{ name }}'>
<input type='submit' name='submit' value='submit'>
</form>
</body>
</html>
Create a show
See the tutorial above for hwo to do this.
Add this code to a show called myname.
function(doc, req) {
if (doc) {
var ddoc = this
var Mustache = require("vendor/couchapp/lib/mustache");
var data = {
title: "The Name",
name: "Bobbert"
}
return Mustache.to_html(ddoc.templates.myname, data)
} else {
return ('nothing here baby')
}
}
Update the document with a new name by ...
So who can complete this step via both the client side and the server side?
Please don't point me to the guide, I need to read it in your words.
Thanks.
Edit:
Although the return value isn't pretty, just posting a form to the update handler will update the document.
You will probably want to look into update handler functions.
An update handler handles granular document transformations. So you can take 1 form, that has one distinct purpose, and only update the relevant fields in your document via the update handler.
Your update handler will need to take a PUT request from your form. A browser can't do this directly, so you'll need some javascript to handle this for you. If you're using jQuery, this plugin can take your form and submit it seamlessly via AJAX using PUT for you.
Inside the function, you can take the fields you are accepting, in this case name and apply that directly to the document. (input validation can be handled via the validate_doc_update function)
Update Handler (in your Design Document)
{
"updates": {
"name": function (doc, req) {
doc.name = req.form.name;
return [doc, "Name has been updated"];
}
}
}
HTML
<form id="myForm" action="/db/_design/ddoc/_update/name/doc_id">...</form>
JavaScript
$(document).ready(function() {
$('#myForm').ajaxForm({
type: "PUT",
success: function () {
alert("Thank you");
}
});
});
Once you've gotten this basic example up and running, it's not much more difficult to add some more advanced features to your update handlers. :)