Having problems with the JavaScript/jquery and c# implementation - javascript

I am following a 3 year old c# course on udemy and am unable to solve the problem regarding the implementation of javascript/jquery code. I am suppose to connect the registration code (via jquery/javascript) with a subscription, however my textbox does not work regardless of the information I insert in it, it is not displaying any text, and it should be displaying different messages such are - Could not register the code., The code was successfully added.
Here is my code:
RegisterCodeController:
public class RegisterCodeController : Controller
{
public async Task<ActionResult> Register(string code)
{
if(Request.IsAuthenticated)
{
var userId = HttpContext.GetUserId();
var registred = await SubscriptionExtension.RegisterUserSubscriptionCode(userId, code);
if (!registred) throw new ApplicationException();
return PartialView("_RegisterCodePartial");
}
return View();
}
_RegisterCodePartial:
#if(Request.IsAuthenticated)
{
<div class="panel panel-primary register-code-panel">
<div class="panel-heading">
<h4 class="panel-title">Register Code</h4>
</div>
<div class="panel-body input-group">
<input type="text" class="form-control" placeholder="Enter code here..." />
<button class="btn btn-primary input-group-btn" type="button" >Submit
<h3 class="panel-title">Submit</h3>
</button>
</div>
<div class="alert alert-danger hidden">Could not register code</div>
</div>
}
RegisterCode.js
$(function () {
var code = $(".register-code-panel input");
function displayMessage(success, message)
{
var alert_div = $(".register-code-panel .alert");
alert_div.txt(message);
if (success)
alert_div.removeClass('alert-danger').addClass('alert-success');
else
alert_div.removeClass('alert-success').addClass('alert-danger');
alert_div.removeClass('hidden');
}
$(".register-code-panel button").click(function (e) {
$(".register-code-panel .alert").addClass('hidden');
if (code.val().length == 0)
{
displayMessage(false, "Enter a code");
return;
}
$.post('/RegisterCode/Register', { code: code.val() },
function (data)
{
displayMessage(true, "The code was successfully added. /n/r Please reload the page.");
code.val('');
}).fail(function (xlr, status, error) {
displayMessage(false, "Could not register the code.");
});
});
});

You are making a POST request but looking at your controller action method it looks like a GET. Thus change your API call $.post('/RegisterCode/Register', { code: code.val() }, to $.get('/RegisterCode/Register', { code: code.val() }, probably and use a HTTP verb explicitly in your action method
[HttpGet]
public async Task<ActionResult> Register(string code)
{
}

Solved, I had the RegisterCode.css file with the same name as RegisterCode.js file, it seems to me this caused some confusion while retrieving data in the Bundle.config, so I renamed the .js file and now it works!

Related

How to remove a validation error beside captcha if the user select the captcha

I am working on an asp.net MVC core web application, and i added a captcha as follow:-
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<span class="msg-error error"></span>
<div id="recaptcha" class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="#ViewData["ReCaptchaKey"]"></div>
</div>
</div>
also i added the following javascript validation to force a required on the captcha:-
$('#getmyestimate').click(function () {
var $captcha = $('#recaptcha'),
response = grecaptcha.getResponse();
if (response.length === 0) {
$('.msg-error').text("reCAPTCHA is mandatory");
if (!$captcha.hasClass("error")) {
$captcha.addClass("error");
}
} else {
$('.msg-error').text('');
$captcha.removeClass("error");
alert('reCAPTCHA marked');
}
})
as follow:-
but what i am trying to do , is that once the user select the captcha to remove the validation error (if any),, so can anyone advice how i can do so?
You can hide inside your callback recaptchaCallback function that you have already added in data-callback attribute in the g-recaptcha class.
var recaptchaCallback = function() {
$('#recaptcha').removeClass("error");
... //Any other code in the callback
}

Is there any better way to show success alert message

I am trying to show Success message , once the data is updated in my application. Success function is working properly , but message is not getting generated. when I click on the save() button, small alert box will display, but message wont appear.
HTML : <div class="alert alert-success" ng-show="successmessage">{{cts.success_info}}</div>
Angular Js:
$scope.successmessage = function(){
$scope.cts = [];
$scope.cts.success_info = "Data Successfully got updated";
}
You defined successmessage as a function, but using it as a value.
If you need to display alert on success call of save function, use success function below. It creates an object with a message and isSuccess flag:
Html:
<div class="alert alert-success" ng-show="cts.isSuccess">{{ cts.message }}</div>
JS:
$scope.success = function() {
$scope.cts = {
isSuccess: true,
message: 'Data Successfully got updated'
};
}
Working demo
You can take advantage of *ngIf if want to display more then just simple string like below:
showMsg: boolean = false;
onSubmit() {
this.userService.createUser(this.addForm.value)
.subscribe( data => {
this.router.navigate(['list-user']);
this.showMsg= true;
});
}
then you can use showMsg boolean to show/hide dive like below
<div class="col-md-6">
<div ng-click=="onSubmit()">
<div class="row" *ngIf="showMsg">
<div class="col-xs-12">
<p class="alert alert-success">
<strong>Registration Success!</strong> Please click here to login!.
</p>
</div>
</div>
<button class="btn btn-success">Add user</button>
</div>
</div>
note that I am using some bootstrap classes for styling.
Yes function must return something . If you want a better option , you can use toast or popover .
Do this,
<div class="alert alert-success" ng-show='cts.showmsg == true'>{{cts.success_info}}</div>
You can use one boolean variable to show/hide message.
Angular Js:
$scope.successmessage = function(){
$scope.cts = [];
$scope.cts.success_info = "Data Successfully got updated";
$scope.cts.showmsg = true;
}
If you want to display in popup or modal, then there is best library in angular called ngDialog

Multiple submits in a MVC application via jQuery

I have 2 anchor links in my view, on which I am trying to hit the HTTP POST method on the controller. The POST method has a condition in which it checks value of a hidden field, and on the basis of the condition, it tries to redirect to different views.
Facing a problem that the value of the hidden field is being NULL everytime, irrespective of the fact that I am setting the value of the hidden field via jQuery.
Below is the code:
<form id="CreateForm" asp-action="CreateForm" method="post" role="form">
<a style="cursor:pointer" onclick="Submit();" id="finishCreateForm">Finish</a>
#Html.Partial("~/_Partial1.cshtml", Model.Contact)
</form>
#section Scripts {
<script>
function Submit() {
$("#CreateForm").submit();
$("#myHiddenField").val = "SubmitCreateForm";
}
</script>
}
<input type="hidden" name="nameHiddenField" id="myHiddenField"/>
In the partial _Partial.cshtml, we have another anchor link, as below:
#model Contact
<span>
<input asp-for="AddressLine1" value="#Model.AddressLine1" />
<span asp-validation-for="AddressLine1"></span>
<a id="find" value="findSubmit" onclick="Find();" style="cursor:pointer">Find</a>
</span>
<script>
function Find() {
$("#CreateForm").submit();
}
</script>
The controller code:
[Route("CreateForm")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateForm(InputViewModel inputVM)
{
if (ModelState.IsValid)
{
//Some business logic stuffs, code removed for brevity
if (inputVM.myHiddenField== "SubmitCreateForm")
{
return RedirectToAction("Test", "Home", new { area = "Shared" });
}
else
{
return RedirectToAction("Search", "MySearch", new { id= response.Id, type= response.Type, area = "Search" });
}
}
else
{
//Some more logic
}
}
I have also added myHiddenField in the model coming to the POST action method, as
public string myHiddenField{ get; set; }
I know I am missing a very basic stuff, please guide accordingly.
Thanks

List<KeyValuePair<string, string>> MVC/Angular form save issues

I have a form to enter a list of key value pairs. When I enter data into the input fields or add a new keyvalue pair everything displays fine on the client side and I can see the Model updating. The problem comes when I go to save the newly created list. The list get passed to the angular save function just fine with all the data in place. The problem occurs between the angular save function and my MVC controller save function. The right number of key value pairs get sent to the MVC controller functions parameters, but all of the information has now been set to null.
So on the client side my model looks like this.
[{"Key":"this","Value":"has"},{"Key":"data","Value":"in"},{"Key":"it","Value":"see"}]
which is what I want, but when it reaches my MVC controller as a parameter it looks like this.
[{"Key":null,"Value":null},{"Key":null,"Value":null},{"Key":null,"Value":null}]
Which is not what I want. Any help with this will be greatly appreciated. Thank You.
Here is my MVC controller function.
public JsonResult SaveSettings(List<KeyValuePair<string, string>> replacementPaths)
{
JobSchedulerConfig config;
config = Biz.GetConfig();
config.ReplacementPaths = replacementPaths;
return null;
}
My Angular controller and save logic.
$scope.save = function () {
SettingsService.saveSetting($scope.settings)
.success(function (data) {
//alert(data);
})
.error(function (error) {
$scope.status = 'Unable to load data: ' + error.message;
});
};
SettingsApp.factory('SettingsService', ['$http', function ($http) {
var SettingsService = {};
SettingsService.getSettings = function () {
return $http.get('#Url.Action("GetReplacementPaths", "Setting")');
};
SettingsService.saveSetting = function (data) {
//alert(data);
alert(data.toSource());
//data = angular.stringify(data);
return $http.post('#Url.Action("SaveSettings", "Setting")', data );
};
return SettingsService;
}]);
And my view markup.
<div ng-app="SettingsApp">
<div ng-controller="SettingsController">
<div ng-repeat="kvp in settings">
<input ng-model="kvp.Key" />
<input ng-model="kvp.Value" />
<button ng-click="delete(settings, kvp)">Delete</button>
</div>
<button class="btn btn-default" ng-click="addSetting()">Add Setting</button>
<button type="submit" name="config" ng-click="save()" class="btn btn-default btn-primary">Save Config</button>
{{settings}}
</div>
</div>
Again thanks for any help.

How to stop redirect from partial page after form submit

Having an issue, I have a partialview named Manage, I load the partial in:
Controller AdminPanel, View AdminProfile like so:
<div id="tab-2" class="tab-pane">
#{Html.RenderPartial("~/Views/Account/Manage.cshtml");
}
</div>
When I click on save changes I get redirected to /Account/Manage, it should be /AdminPanel/AdminProfile?
Not sure if controller is returning the correct redirect or information for the json if I try to use a ajax script:
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
public ActionResult Manage(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("AdminProfile", "AdminPanel");
//ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("AdminProfile", "AdminPanel", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("AdminProfile", "AdminPanel", new { Message = ManageMessageId.ChangePasswordSuccess });
}
catch (Exception)
{
ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
}
}
}
// If we got this far, something failed, redisplay form
//return PartialView("Manage", model);
return Json(new { redirectTo = Url.Action("AdminProfile", "AdminPanel") });
}
This is the partial page that is loaded:
#model LocalPasswordModel
#{
ViewBag.Title = "Change Password";
}
<section class="hgroup">
<div class="panel-body">
<h1>#ViewBag.Title</h1>
<ul class="breadcrumb pull-right top-right">
<li>You're logged in as <strong>#User.Identity.Name</strong></li>
</ul>
<ul class="message-success">#ViewBag.StatusMessage</ul>
#using (Html.BeginForm("Manage", "Account", Form.Post, new { #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label class="col-sm-2 control-label">Old Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.OldPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.NewPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-2">
<input type="submit" class="btn btn-primary" value="Change password" />
</div>
</div>
}
</div>
</section>
The script below is placed in the _LayoutPage however as mentioned in the comments it is not doing anything.
<script type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("Manage", "Account")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
// The operation was a success on the server as it returned
// a JSON objet with an url property pointing to the location
// you would like to redirect to => now use the window.location.href
// property to redirect the client to this location
window.location.href = result.redirectTo;
} else {
// The server returned a partial view => let's refresh
// the corresponding section of our DOM with it
$(".tab-2").html(result);
}
},
error: function () {
}
});
</script>
All I am trying to do is stop the redirect after I submit, I have opened this to a bounty. It would be nice if you could also include how I could recieve the status messages back aswell after a user hits submit.
For instance user hits save changes > saves to the server > messages are then sent back to the partial page (all without redirecting)
Firstly, you need to decorate your POST action result as a post.
[HttpPost]
public ActionResult Manage(LocalPasswordModel model){
Secondly, you can get rid of the javascript altogether by
testing the validity of the form submit result within your controller
and this will manage whether the user is redirected or not.
[HttpPost]
public ActionResult Manage(LocalPasswordModel model){
if(condition to redirect){
return RedirectToAction("AdminProfile", "AdminPanel");
}
return View(model);
}
Lastly, I cannot see where you've actually put you jquery.
It needs to be put at the end of your form page, in your script section.
You mention it's in your layout page?
I think this link may also help, jQuery.post(), also event.preventDefault() is also useful to prevent form submission client side.
To control specifically where you want to redirect to, add redirects at every place there is a result, example: please note I am only returning to the adminprofile as this is what the op wants
if (changePasswordSucceeded)
{
return RedirectToAction("AdminProfile", "AdminPanel", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
return RedirectToAction("AdminProfile", "AdminPanel");
}
As a sidenote, you need to think through your program flow to decide how you want to manage invalid attempts, etc.
Is it because when you press save its doing a regular http post to the server to the Account/Manage page so you are being redirected. So your javascript is never actually running?
try using Ajax.BeginForm or changing the save button to use your javascript.
If you are posting your form data using AJAX then simply in the submit function
<form onsubmit="mysubmitfunc(event)" ....>
And in the submit function
function mysubmitfunc(e)
{
e.preventDefault();
/*
YOUR AJAX CODE GOES HERE
*/
return false; //last line in the function
}
Use ajax submit in the right way, how? attach to form submission event, catch submit event, stop the post, post it from javscript, and process the response at success.
Replace your _LayoutPage js with next, make sure you are using ID to identify the form, if not this javascript may affect other forms.
$(function() { //shorthand document.ready function
//recommended to use Id on form identification not class... search on google how to
//attach handler on form submit
$('.form-horizontal').submit(catchSubmit);
//custom handler for form submit
function catchSubmit(event) {
event.preventDefault(); //stop html form post
// ajax post with serialized form
$.post($(this).attr("action"),
$(this).serialize(),
postSuccessHandler
);
}
//redirect decizion
function postSuccessHandler(data) {
if (data.redirectTo) {
window.location.href = data.redirectTo;
} else {
$(".tab-2").html(data);
}
}
});
You can also move the html button to outside of the form.

Categories

Resources