How to use #ReCaptcha with Ajax Form in MVC3? - c#

I am trying to use ReCaptcha from Microsoft.Web.Helpers. If I load the entire page it renders correctly, but if I load the page with an ajax request it disappears.
Example (/home/index)
<div id="bla">
#Ajax.ActionLink("reload with ajax", "index", new AjaxOptions() { UpdateTargetId = "bla" })
#ReCaptcha.GetHtml(publicKey: "xxx")
</div>
If I enter /home/index the captcha appears. If I click the button reload with ajax the ReCaptcha disappears...
The page is loaded for the first time
reload with ajax was clicked, the contents of the page change to /home/index, in other words, the entire page reloaded asynchronous and the captcha is gone
Is there a way to fix this or a decent captcha helper for MVC 3?

I've replaced the helper with javascript. ReCaptcha script
<div id="captcha"></div>
<input type="submit" value="Send" />
<script type="text/javascript">
Recaptcha.destroy();
Recaptcha.create("publicKey", "captcha", {});
</script>
And the Controller is still the same
if (ReCaptcha.Validate("privateKey"))
{
}
So when it loads the view partially it executes this scripts and render correctly every time.
Thanks for the help #Bala R

I faced the same issue and the quickest solution i found is using what it is proposed above and add to it this part of code in the top of your page within the handler "EndRequestHandler" proposed by the .net javascript api ( http://msdn.microsoft.com/en-us/library/bb311028(v=vs.100)).
With this solution the backend validation always works.
Here is the code I've used :
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (Recaptcha != null) {
Recaptcha.destroy();
Recaptcha.create("public_key", "captcha", {});
}
}
</script>
I hope this could help someone...

Related

Jquery not working on cshtml to pop up dialog box

This is the editor for the startdate #Html.EditorFor(model => model.startDate) and I have jquery blow, the code for the query is on the page and when I run the program the calender pop up does not come up, both code are on the dame cshtml page
<meta charset="utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(function() {
$( "#startDate" ).datepicker();
});
</script>
Replace
#Html.EditorFor(model => model.startDate)
with
#Html.EditorFor(model => model.startDate, new { #class="startDate" })
because you have not giveen a class to that field and change your jQuery to
$(function() {
$( ".startDate" ).datepicker();
});
so # becomes . as we are using a class.
You need to verify that all your external scripts loaded properly. I suggest you install Fiddler and then watch your requests and see if all of them loaded. If that all is ok then you need to check that the scripts actually load before your call for the datepicker function. If you're using MVC 4 and sections feature that would mean that all you javascript code needs to go into the SCRIPTS section which is placed on your view AFTER the calls to load jquery and jquery-ui libraries. Use Goggle Chrome's console to verify that there are no javascript errors.
Looking at the code you posted here everything should be working. I've done this millions of times and every time I had a problem it was because I was missing a JQuery library reference or I wasn't loading them in proper order.

MVC2 C#: How can I populate a contentplaceholder with html from a file?

So.. The issue I have came across is I am migrating a client's web app to MVC2, and the original method for displaying html content is not capable of working with MVC so I am needing to update it. The functionality I need is like so: There is a side nav that will contain the actions, and say the user clicks on "FooBar" it will populate the "mainContent" placeholder with the "FooBar.html" file from a document directory. I would like to do this with no postbacks as well if it is possible. Any ideas?
You may use jQuery ajax to load the pages when user clicks on the link. load() function will be ideal here.
It is just HTML and javascript. Nothing specific to ASP.NET MVC
//Include jQuery library
<div>
<a href="Home/about" class="aLink" >About</a>
<a href="Home/FAQ" class="aLink" >FAQ</a>
<a href="Home/Contact" class="aLink" >Contact</a>
</div>
<div id="mainContent">
</div>
<script type="text/javascript">
$(function(){
$("a.aLink").click(function(e){
e.preventDefault(); // prevent the default navigation behaviour
$("#mainContent").load($(this).attr("href"));
});
});
</script>

C# Function then Javascript Function on event (ASP.NET)

I'm having a difficult time getting around AutoPostBack with ASP.NET components, and was hoping someone can help. I've looked through multiple queries but nothing is really helping.
I have a 'Submit' button on my page that when clicked should do 2 things:
1. Run a server-side C# function that updates a bunch of <asp:Labels in a div tag.
2. Run a javascript animation that moves stuff around and makes the <div tag visible.
My functions work just fine by themselves, however my issue is with autopostback. If I use an <asp:Button the postback refreshes and the javascript animation is undone along with it. If I use an <input type="button" tag I am unable to run both the C# and Javascript functions. I've tried the following:
<input type="button" runat="server" onclick="c#function" onclientclick="javascriptFunction(); return false;"
** runat="server" seems to just enable postback on that button
<asp:Button
** C# function uses Page.ClientScript.RegisterStartupScript to invoke javascript function, but postback defeats the animation.
I'm hoping to keep the javascript animations as they make the interface very clean and intuitive, so any help in keeping it is greatly appreciated. Any suggestions?
You may use ajax. You can pass values to the server page thru ajax and let the server page handles (insert a record in table / send an email to someone / whatever....) it for you and return a result to you. Till you get your result. you can show a "Processing..." Message to the user.
Here is a plugin to have the block effect.
http://jquery.malsup.com/block/
The below is a small example of how to do it in ajax (with jquery)
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<head>
<body>
<input type="button" id="btnGetProd" value="Get Products" />
<div id="divProducts"></div>
<script type="text/javascript">
$("#btnGetProd").click(function(){
$("#divProducts").html("Processing your request....</div>").fadeIn(100, function ()
{
$.ajax({
url: "myajaxserverpage.aspx?mode=getprodcusts&category=3",
success: function (data) {
$("#divProducts").html(data).fadeIn(100);
},
error: function (req, textStatus, error) {
alert("Some error occured");
}
})
});
});
</script>
</body>
</html>
and you should have a page called myajaxserverpage.aspx which returns the content (ex: A list of products) for the div called "divProducts"
What the above code does is , When the user click on the button, it shows the text "Processing your request..." in the div and then make an ajax call to the aspx page.Once it receives the response, it put that to the div and then do a fadeIn effect.
what you are experiencing is expected. the browser will execute the javascript and then send a request to the server. the server processes the request and send a response. the client will then render the response. At this point any UI changes you made are discarded because a new request was received.
To get around this you will need to incorporate ajax into your page.
alternative way to reach your needs
1.let button do only javascript function
2.let javascript function do the postback after u finish your animation
ajax is not requirement

MVC ajax not working

I have this code in my .cshtml:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<span id="status">No status</span> <br />
#Ajax.ActionLink("Server Date", "ServerTime", new AjaxOptions { UpdateTargetId = "status"})
This is the method in controller:
public string ServerTime()
{
return "Server date: " + DateTime.Now;
}
When I click the hyperlink, the reponse comes on a different page i.e the DOM is not updated. Instead, I get redirected to Home/ServerTime.
Can anybody tell me why is this happening? The script files are correctly downloaded and I checked it in Firebug.
Thanks in advance :)
asp.net mvc 3 by default uses unobtrusive ajax. So you should include script jquery.unobtrusive-ajax.min.js, not the MicrosoftMvcAjax ones. As the script is not included, javascript does not parse the ajax link data, so it stays as ordinary link.
Add OnSuccess method parameter in AjaxOptions

C# ASP.NET MVC AJAX Login Form

I am using the MVC Ajax.BeginForm("LogOn", "Account", new AjaxOptions { UpdateTargetId="updateajax" }) <div id=updateajax/> so it only updates to that area. The login form is the ajax.beginform. But can you cancel the AjaxRequest inside the controller. What I wanted is that when I am loggin in the ajax, it will only update the validations but when the login is successful I want the whole page to redirect or update again. In my controller I return the entire page when the login is successful but that put the whole content inside the updateajax div. What can I do to solve this problem? I just want to stop the ajax call when the login is successful.
You sort of have to either redirect or update the whole body of the page.
Or you can wrap the whole body content in a div and ajax update that one. My suggestion is to go ahead and redirect, because if you have scripts that run on load, you would have to manually call them.
<body>
<div id="ajaxUpdatedPanel">
<% using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions {
UpdateTargetId="ajaxUpdatedPanel",
OnSuccess = "redirectTo" }) { %>
....
....
<script type="text/javascript">
function redirectTo() {
window.location = "your_redirect_url";
}
</script>
<div>
</body>

Categories