Refreshing captcha reloads the whole page - asp.net-mvc

I'm new to JSON and jqueries.
I created a captcha as below in cshtml file
<div class="row-fluid">
<div class="span3"></div>
<iframe id="CaptchaIfram" src="#Url.Action("ShowCaptchaImage")" scrolling="no"></iframe>
<div>
<div class="span3"></div>
<input id="RefreshCaptcha" type="submit" onclick="captcha()" value="Refresh" class="btn btn-success" />
</div>
</div>
<script type="text/javascript">
function captcha()
{
document.getElementById("CaptchaIfram").contentDocument.location.reload(true);
}
</script>
in Controller:
public Captcha ShowCaptchaImage(int width, int height, int totalcharacters)
{
return new Captcha(width, height, totalcharacters);
}
Its working fine and if I click on refresh button, whole page getting refreshed as I'm using Url.Action method.
To avoid this, I used JSON as below. But image is not getting displayed.
Can anybody let me know where I need to correct.
<div class="row-fluid">
<div class="span3"></div>
<iframe id="CaptchaIfram" onload="showCaptcha()" scrolling="no"></iframe>
<div>
<div class="span3"></div>
<input id="RefreshCaptcha" type="submit" value="Refresh" onclick="showCaptcha()" class="btn btn-success" />
</div>
</div>
<script type="text/javascript">
function showCaptcha()
{
var url = "/ESignature/ShowCaptchaImage";
var target = '#CaptchaIfram';
$.getJSON(url, { width: 200, height: 35, totalcharacters: 5 }, function (data) {
document.getElementById("CaptchaIfram").src = data;
});
}
</script>
public JsonResult ShowCaptchaImage(int width, int height, int totalcharacters)
{
return Json(new Captcha(width, height, totalcharacters), JsonRequestBehavior.AllowGet);
}

I changed the type of refresh button to client side button as below. It didn't refresh the whole page.
No Json functions are required. (second code block in my question)

Related

How to Fix message is not send Server to Client In SignalR Asp.net core 6

I do all thing but my message is not send from Server To client. I have two controller One is client and Another One is server controller they both have different View there have another Index view in server Controller And different Index view in Client .In server view I add Form And submit button and client view Used as result whenever I fill form and submit there result will be shown on client view page but it doesn't Work
This Is My Hub
public class NotificationHub:Hub
{
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("ReceiveMsg", message);
}
}
This Is My client View Page
<h1>Client App</h1>
<div id="servermsg">
<ul id="msgList">
</ul>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/ClientNotification.js"></script>
This is My JavaScript File
"use strict";
var connection = new signalR.HubConnectionBuilder()
.withUrl("/notificationHub")
.build();
connection.start();
console.log(connection);
connection.on("ReceiveMsg", function (msg) {
console.log('message ',msg)
var li = document.createElement("li");
li.textContent = msg;
document.getElementById("msgList").appendChild(li);
})
var el = document.getElementById("#form-submit-btn");
if (el) {
el.addEventListener('click', () => {
connection.invoke("SendMessage", document.querySelector("#message-input").value);
});
}
This is my Server View Page
#model SignalR.Models.Notification
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<h4>Notification</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Index">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Message" class="control-label"></label>
<input asp-for="Message" id="message-input" class="form-control" />
<span asp-validation-for="Message" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" id="form-submit-btn" value="Send" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/ClientNotification.js"></script>
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
This is my Model
public class Notification
{
public string? Message { get; set; }
}
Please What is the issue in My code that Server To client doesn't work
Change your js code:
var el = document.getElementById("#form-submit-btn");
to:
var el = document.getElementById("form-submit-btn");

How to perform a login identification process in the best way?

I have 2 inputs boxes: Public key (user name) and Private key (password). Also I have a hidden warning label.
This is my code (and it's perfectly working ):
<script language="javascript">
function SendLoginData() {
document.getElementById("LoginErrorLabel").style.display = "none";
var url = "/DappAccount/CheckAccount";
$.post(url, { PublicKey: $("#public_key_input").val(), PrivateKey: $("#private_key_input").val() }, function (data) {
if (data == false) {
document.getElementById("LoginErrorLabel").style.display = "block";
return;
}
else {
document.getElementById("loader").style.display = "block";
$("#myform").submit()
}
});
}
</script>
<div class="container">
#using (Html.BeginForm("AccountMainPage", "DappAccount", FormMethod.Post, new { #id = "myform" }))
{
<div class="row justify-content-center">
#Html.TextBoxFor(m => m.publicKey, new { id = "public_key_input", placeholder = "Ethereum Public Key", required = "required" })
</div> <br />
<div class="row justify-content-center">
#Html.TextBoxFor(m => m.privateKey, new { id = "private_key_input", placeholder = "Ethereum Private Key", required = "required", type = "password" })
</div> <br />
<div class="row justify-content-center">
<img id="loader" style="display: none;" src="https://s5.gifyu.com/images/Loader5a73d3b26568dbc4.gif" alt="Loader5a73d3b26568dbc4.gif" border="0" />
</div> <br />
}
<div class="row justify-content-center">
<input id="submit" type="button" value="Login" class="btn btn-primary" onclick="SendLoginData()" />
</div>
<label id="LoginErrorLabel" style="color: red; display: none;">*Wrong login detail !</label>
</div>
What I'm doing here is:
1) Send username&password to the 'CheckAccount' method in the controller, the method returns true/false.
2) If false, show label,
if true, show gif image and send again the details to ActionResult (=AccountMainPage) which returns a new view.
I just wonder, is there a better/shorter way to do it using one post or one method? I heard something about the partial views in MVC, no idea what to do with it. People told me that what I did here is too old for MVC

Saving data through AngularJS

Update:
I have replaced <input type=submit to <button ... and also remove the form tag from my html, after modifying my code i do not see it executing my JS and I have a debugger line in the code and it does not break....
I'm trying to POST data and I have all the code in placed and wired-up correctly (I believe) but when I try to Submit my page # My page gets refreshed, I don't see any event is firing and I have set debugger in the JS, and I do not see any JS error in developer tool
What I'm missing here apart from my code?
here is my code:
//HML code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../AppScripts/RequesterAdd.js"></script>
</head>
<body>
<form>
<div ng-app="requesterAddModule" ng-controller="requesterAddController" class="container">
<h2> add requester</h2>
<div ng-show="ShowMessage">Record saved Successfully</div>
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HostModel</h4>
<hr />
<div class="form-group">
<div>First Name:</div>
<div class="col-md-10">
<input type="text" ng-model="FirstName" required class="form-control input-lg" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<div>Middle Name:</div>
<div class="col-md-10">
<input type="text" ng-model="MiddleName" required class="form-control input-lg" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<div>Last Name:</div>
<div class="col-md-10">
<input type="text" ng-model="LastName" required class="form-control input-lg" placeholder="Last Name" />
</div>
</div>
<div class="form-group">
<div>eMail Address:</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="text" ng-model="Email" required class="form-control input-lg" placeholder="Email Address" />
</div>
</div>
<div class="form-group">
<div>Is Host Active:</div>
<div class="col-md-10">
<input type="checkbox" ng-model="Active" required class="control-label col-md-2" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</form>
</body>
</html>
//JS:
var requesterAddModule = angular.module("requesterAddModule", []);
requesterAddModule.factory('requesterAddService',
['$http', function ($http) {
return {
addRequester: function (reqesterData) {
console.log(reqesterData);
debugger;
$http({
url: 'PersistRequester',
method: 'POST',
data: reqesterData
}).then (function (response) {
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
},
function(response) {
//failed
}
);
}
};
}]);
requesterAddModule.controller('requesterAddController', ['$scope', '$http', '$window', 'requesterAddService', function ($scope, $http, $window, requesterAddService) {
$scope.addRequester_ClickEvent = function () {
var req = {};
debugger;
req["FirstName"] = $scope.FirstName;
req["MiddleName"] = $scope.MiddleName;
req["LastName"] = $scope.LastName;
req["Email"] = $scope.Email;
req["Active"] = $scope.Active;
requesterAddService.addRequester(req);
}
}]);
//MVC Server side code:
[HttpPost]
public JsonResult PersistRequester(Requester requester)
{
var req = requester;
//if (ModelState.IsValid)
// {
req.CreatedDateTime = DateTime.Now;
db.Requesters.Add(requester);
db.SaveChanges();
return Json(new { Status = "Success" });
//}
}
You're using a form without a method and action which will by default post to the current url. I would highly recommend not to use a form or at least not using an <input type="submit" /> which will default in all the browsers to submit the form.
You're clearly using Bootstrap 3 here so why not just remove the form tag and the submit button and replace it with another element which will not trigger the form post and style it with class="btn btn-primary". Some could argue against this practise along the graceful degradation guidelines but since this particular form is not built from ground up to support the non-js scenario, it is best not to allow browser submit at all.
Also, in your service where you're doing the actual post, you specifically tell the page to reload.
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
You should pass this data back to the viewmodel so that the view can re-render and display the response.
If you change the url, the view state is lost and the page will simply render again to the initial state.
instead line
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
please do
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" class="btn btn-primary" >Create</button>
I've just tested and is working for me replace:
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
with
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" value="Create" class="btn btn-primary" >submit</button>
and I've change a bit your service to :
requesterAddModule.factory('requesterAddService',
['$http', function ($http)
{
return {
addRequester: function (reqesterData)
{
console.log(reqesterData);
debugger;
$http.post('PersistRequester', reqesterData).then(function (response)
{
if (response !== 'undefined' && typeof (response) == 'object') {
window.location.href = '/'
}
},
function (response)
{
//failed
}
);
}
};
}]);
it's posting to /home/PersistRequester if method 'PersistRequester' exist in other controller ie : foo controller change
$http.post('PersistRequester', reqesterData).then(function (response)
to $http.post('foo/PersistRequester', reqesterData).then(function (response)

How to passing form params from formRemote to remoteFunction in GSP

example is very simple.
select the two search condition and return a table with pagination, the whole page will not refresh.
so i use the grails formRemote to submit the form, and the control return the gender with template and it work well. However, the pagination i want to use Jquery, but i cant pass the formRemote params to the remoteFunction using onSuccess method in formRemote.
Here it is the code:
<div class="formSep col-md-12">
<g:formRemote update="searchResult" class="form-inline" role="form" name="form"
url="[controller: 'autoRateRecord', action: 'search']" onSuccess="initPagination(data)">
<div class="form-group col-lg-2">
<g:select class="form-control" name="notified" from="${['done', 'undone']}"
noSelection="${['null': 'Oops']}">
</g:select>
</div>
<div class="form-group col-lg-2 pull-right">
<button type="submit" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-search"></span> search
</button>
</div>
</g:formRemote>
</div>
<div id="searchResult">
<g:render template="searchList"/>
</div>
<script type='text/javascript'>
function initPagination(data) {
console.log("------> " + data)
$("#Pagination").pagination(10, {
callback: getRecordList(1),
prev_text: "prev",
next_text: "next",
items_per_page: 15,
num_edge_entries: 1
});
}
**!!!!!!! need formRemote data !!!!!!!**
function getRecordList(page_index) {
<g:remoteFunction controller="autoRateRecord" action="search" update="searchResult" params="'page='+page_index"/>
}
// On load, style typical form elements
$(function () {
});
</script>
the controller code is:
def search = {
log.info(ToStringBuilder.reflectionToString(params))
// logic .....
render(template: "searchList", model: [
autoRateRecords: result,
total : result.totalCount
])
}
I would change the pagination script to something like
$("#pageHiddenFieldId").val(pageNo);
$("#myForm").submit();

jquery ui tab select method not working

I have two tabs with a submit button on each tab. When the button is clicked, I need to reload the content of that specific tab to get updated data from the server.
if (validStatus()) {
$.ajax({
//...
success: reloadTab
});
}
function reloadTab() {
var currentTab = $("#tabs").tabs("option", "active");
alert(currentTab);
$('#tabs').tabs('select', currentTab);
alert(currentTab);
}
When the button is clicked, the tab doesn't refresh. I see the first alert but not the second.
HTML is as follows:
Head:
<link rel="stylesheet" href="#this.Url.Content("//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css")" />
<script>
$(function () {
$("#tabs").tabs();
});
</script>
Body:
<div id="tabs">
<ul>
<li>The first tab</li>
<li>the second tab</li>
<li>Success</li>
</ul>
<div id="Success">
testing
</div>
<div id="Tab1">
<fieldset >
<legend>Overview</legend>
<input type="button" id="submit1" value="submit" />
<br />
</fieldset>
<fieldset style="width: 700px;">
<legend>Overview</legend>
<div>
<table >
//updated with ajax
</table>
</div>
</fieldset>
<script>
//reloadTab is in here
</script>
</div>
<div id="Tab2">
<fieldset style="float:left; width:300px;">
<input id="submit2" type="button" value="submit"/>
</fieldset>
<fieldset style="float:left;">
<legend>Overview</legend>
<table>
//updated with ajax
</table>
</fieldset>
<script>.....</script>
</div>
Turns out tabs.('select', ...) is deprecated, using tabs.('option', 'active', index) fixed my issue. Solution found in this comment: https://stackoverflow.com/a/16033969/1463649
Do you see anything in the console of your browser? What browser are you using?
Try this to help you with the debugging.
function reloadTab() {
console.log($('#tabs')); // if this is an empty object, the element doesn't exist when you call this function
console.log($('#tabs').tabs()); // if this doesn't return 'function', you haven't included a library properly, maybe jquery ui, or jquery, or you're using an old version or something
console.log(currentTab); // if this is undefined then something went wrong and no tab is active
var currentTab = $("#tabs").tabs("option", "active");
alert(currentTab);
$('#tabs').tabs('select', currentTab);
alert(currentTab);
}

Resources