How to pass data from Action to Ajax success function in mvc4? - javascript

hi i am want to when login succesfully then call my success function otherwise call error function
View code here
<div class="container">
<div class="login-container">
<div class="avatar"><img src="#Url.Content("~/Content/images/download.jpeg")" style="max-width:95%;" /></div>
<div class="form-box">
#using (Html.BeginForm())
{
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control", #id="userid", #placeholder = "Username", #required = "required", #maxlength = "20" })
</div>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
#Html.PasswordFor(m => m.Password, new { #class = "form-control", #id = "userpass", #placeholder = "Password", #required = "required", #maxlength = "20" })
</div>
<button class="btn btn-info btn-block login" type="submit" id="login-btn"><i class="glyphicon glyphicon-log-in"></i> Login</button>
}
</div>
</div>
ajax code here:
<script>
$(document).ready(function () {
$('#login-btn').click(function () {
var dataObject = {
Id: $("#userid").val(),
Password: $("#userpass").val()
};
$.ajax({
url: '#Url.Action("Login","Account")',
type: "POST",
data: dataObject,
dataType: "json",
success: function (data) {
if (data.toString() == "login") {
toastr['success']("Login Successfully");
}
else if (data.toString() == "error") {
toastr['error']("Id or Password is incorrect");
}
},
error: function () {
toastr['error']("Hello");
}
});
});
});
Controller Code here:
[HttpPost]
public ActionResult Login(LoginMaster model)
{
string message = "";
if (ModelState.IsValid)
{
try
{
var user = from emp in db.LoginMasters
where emp.UserId == model.UserId && emp.Password == model.Password
select emp;
var rol = user.FirstOrDefault();
if (rol != null)
{
var realrol = rol.Role;
if (realrol == "admin")
{
message = "login";
return RedirectToAction("Index", "Home");
}
else if (realrol == "user")
{
Session["userid"] = rol.UserId;
message = "login";
return RedirectToAction("User", "Home");
}
}
else
{
message = "error";
}
}
catch (Exception ex)
{
ViewBag.cath = ex.Message;
}
}
else
{
message = "error";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
return View();
i am want to when we login succesfully that time call this
toastr['success']("Login Successfully");
and when login fail that time call
toastr['error']("Id or Password is incorrect");
please solve this problem.
thanks in advance!

Assuming your controller code hits the part that returns the json then you can access it via .Data:
success: function (data) {
if (data.Data == "login") {
toastr['success']("Login Successfully");
}
else if (data.Data == "error") {
toastr['error']("Id or Password is incorrect");
}
}
You set the .Data property within your code here:
new JsonResult { Data = message ...
and the problem with your success call is that it is testing the entire json object, not the .Data property.
data.toString() == "login"

no sir our problem is our Action where we can put hit point that is not run in a sequence our this point is firstly execute
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
then after execute this part
try
{
var user = from emp in db.LoginMasters
where emp.UserId == model.UserId && emp.Password == model.Password
select emp;
var rol = user.FirstOrDefault();
if (rol != null)
{
var realrol = rol.Role;
if (realrol == "admin")
{
message = "login";
return RedirectToAction("Index", "Home");
}
else if (realrol == "user")
{
Session["userid"] = rol.UserId;
message = "login";
return RedirectToAction("User", "Home");
}
}
else
{
message = "error";
}
}
catch (Exception ex)
{
ViewBag.cath = ex.Message;
}
so problem is we can not set correct string in message variable so please first of all you can make a sample in js fiddle then provide me link

As you have used this code in your script. :
var dataObject = {
Id: $("#userid").val(),
Password: $("#userpass").val()
};
if your LoginMaster model contains Id & Password it'll display data.
If you have UserId & Password then you have to change your code in script like below.
var dataObject = {
UserId: $("#userid").val(),
Password: $("#userpass").val()
};
In short replace Id with UserId.

Related

refreshApex not trigger when called from parent lwc

I have a button on the parent lwc. When called, it will call a method on the child lwc to perform data update via apex method. Once done, it calls refreshApex to refresh the data on the lightning datatable. RefreshApex will not trigger for some reason.
Now, if I use the child's save button to save the changes, refreshApex will trigger and data will update without any issues.
Appreciate your help!!!
enter image description here
PARENT COMPONENT
</div>
<footer class="slds-modal__footer">
<lightning-button label="Save" variant="brand" onclick={saveModal} class="slds-m-left_x-small"></lightning-button>
<lightning-button label="Cancel" variant="neutral" onclick={closeModal} class="slds-m-left_x-small"></lightning-button>
</footer>
PARENT JS
saveModal() {
//firing a child method
this.template.querySelector("c-reuse-license-key-table").testHandleAction();
}
CHILD COMPONENT
<template if:true={quotelinelist}>
<div class="slds-grid_align-end" style="height: 500px; overflow: auto;">
<lightning-datatable key-field="Id"
data={quotelinelist}
columns={columns}
onsave= {testHandleAction}
oncellchange= {handleRowAction}
draft-values={fldsItemValues}
hide-checkbox-column="true"> <!--suppress-bottom-bar="true"-->
</lightning-datatable>
</div>
</template>
CHILD JS
#wire(getQuoteLinesList,{quoteId: '$parentRecordId', actionType: '$actionTypeForWire'})
cons(result) {
console.log('check result 1 ', result)
this.wiredDataResult = result;
if(result.error) {
console.log('inside wire error')
//this.quotelineList = undefined;
}
else {
console.log('inside else error')
this.quotelinelist = result.data;
}
}
handleRowAction(event) {
lKeyDraftList.push(event.detail.draftValues);
}
#api async testHandleAction() {
let strOriginalKeyValues = JSON.stringify(qlInList);
let strlKeyDraftList = JSON.stringify(lKeyDraftList);
let strDraftValue = [];
lKeyDraftList.forEach(function(c){
console.log('check c', c);
c.forEach(function(c2){
console.log('check c2', c2);
strDraftValue.push(c2);
});
});
await updateQuoteLines({IdToObjectForDraftValues : JSON.stringify(strDraftValue)}) //, IdToObjectForOriginalValues: strOriginalKeyValues
.then(result => {
const toast = new ShowToastEvent({
title: 'Success',
message: 'Records Updated Successfully!!',
variant: 'success'
});
this.dispatchEvent(toast);
this.actionTypeForWire = 'update';
return refreshApex(this.wiredDataResult).then(() => {
console.log('after refresh apex')
this.fldsItemValues = [];
});
})
.catch(error => {
console.log('error');
const toast = new ShowToastEvent({
title: 'Error',
message: 'An Error Occurred!!' + error.message,
variant: 'error'
});
this.dispatchEvent(toast);
}).finally(() => {
console.log('inside final', this.fldsItemValues);
});
}
APEX Controller
#AuraEnabled(cacheable=true)
public static List<SBQQ__QuoteLine__c> getQuoteLinesList(Id quoteId, String actionType) {
List<SBQQ__QuoteLine__c> qLineList = new List<SBQQ__QuoteLine__c>();
if(quoteId != null){
qLineList = [SELECT Id,Name,SBQQ__ProductName__c,SBQQ__Quantity__c,Reused_License_Key__c
FROM SBQQ__QuoteLine__c
WHERE SBQQ__RequiredBy__c != NULL
AND SBQQ__Quote__c = :quoteId
ORDER BY SBQQ__ProductName__c];
}
Boolean callLPUtility = true;
for(SBQQ__QuoteLine__c ql : qLineList) {
if(ql.Reused_License_Key__c != null) {
callLPUtility = false;
break;
}
}
if(callLPUtility == true && actionType == 'begin') {
LicenseProductUtility.toMapLicenseKeyForRenewal(qLineList, getSubscriptionsList(quoteId));
}
return qLineList;
}
#AuraEnabled
public static void updateQuoteLines(String IdToObjectForDraftValues) { //String IdToObjectForOriginalValues
List<Object> items = (List<Object>) JSON.deserializeUntyped(IdToObjectForDraftValues);
List<SBQQ__QuoteLine__c> qlList = new List<SBQQ__QuoteLine__c>();
List<Map<String, Object>> theJsonMapList = new List<Map<String, Object>>();
for(Object itemObj : items) {
theJsonMapList.add((Map<String, Object>) itemObj);
}
for(Object o : theJsonMapList){
SBQQ__QuoteLine__c q = new SBQQ__QuoteLine__c();
q.Id = ((Map<String, Object>) o).get('Id').toString();
q.Reused_License_Key__c = ((Map<String, Object>) o).get('Reused_License_Key__c').toString();
qlList.add(q);
}
Savepoint sp = Database.setSavepoint();
if(!qlList.isEmpty()){
try {
update qlList;
} catch (Exception e) {
Database.rollback(sp);
System.debug('An exception occurred updateQuoteLines: ' + e.getMessage());
}
}
}

dropdown not populating after ajax call in mvc5 platform

Have a good day. I here because of I am suffering a problem. That is I am working with a cascade dropdown in a user controller. When I change the MotherCompany then Division will appear as per mothercompany. My Controller end code is working fine. But in Front End Dropdown is not populating. What I am doing wrong can Anybody help me please. ( Sorry for my BAD English )
controller code:
[HttpPost]
public JsonResult getDivision(int id)
{
var division = db.Divisions.Where(x => x.MotherCompanyId == id).ToList();
List<SelectListItem> listDivision = new List<SelectListItem>();
listDivision.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
if (division != null)
{
foreach (var x in division)
{
listDivision.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
}
}
return Json(new SelectList(listDivision, "Value", "Text"), JsonRequestBehavior.AllowGet);
}
My Javascript here:
<script type="text/javascript">
$(document).ready(function () {
$("#MotherCompanyId").change(function () {
$("#divisionId").empty();
$.ajax({
url: '#Url.Action("getDivision")',
async: true,
type: "POST",
dataType: "json",
data: { id: $("#MotherCompanyId").val() },
success: function (data) {
$.each(data, function (i, val) {
$('select#divisionId').append(
$("<option></option>")
.attr("Value", val.Value)
.text(val.Text));
});
},
error: function (xhr) {
alert(" An error occurred.");
},
});
return false;
})
});
View: `
<div class="form-group MotherCompanyId">
#Html.LabelFor(model => model.MotherCompanyId, new { #class = "" })
#Html.DropDownList("MotherCompanyId", ViewBag.MotherCompanyId as SelectList, "Select a MotherCompany", htmlAttributes: new { required = "required", style = "display:none;width:100%;" })
#Html.StarkDropDownAjaxLink("/MotherCompany/Create", "AddMore", "")
</div>
<div class="form-group DivisionId">
#Html.LabelFor(model => model.DivisionId, new { #class = "" })
#Html.DropDownList("divisionId", new SelectList(string.Empty, "Value", "Text"), "--Select Division--", new { style = "display:none;width:100%;" })
#Html.StarkDropDownAjaxLink("/Division/Create", "AddMore", "")
</div>`

Forgot password Page

Good Afternoon every one,
I know this is very old question but I am very new to programming.Could any one help me
I have a forgot password page and it contains
Save button type is submit,Go to login link and one "User Name" of type input text.
Now when I click on save it should execute the following code
enter code here public VWUser ResetPassword(string userName)
{
using (var db = new AppDB())
{
var data = db.VWUsers.FirstOrDefault(m => m.UserName == userName && m.TenantId==Helper.TenantId);
if (data == null)
throw Helper.AppException(ExceptionTypes.Data, LocalText.ERR_UnAuthorizedAccess);
var password = SecurityManager.GenerateRandomPassword();
//data.Password = SecurityManager.Hash(password);
data.Password = SecurityManager.EncryptData(password);
db.SaveAndAssertChanges();
var result = db.VWUsers.First(x => x.UserName == data.UserName && x.TenantId ==Helper.TenantId);
result.xPassword = password;
return result;
}
}
And my Js will be like below
$(document).ready(function () {
debugger;
$("#frm-data").validate({
rules: {
UserName: {
required: true,
maxlength: 50,
},
},
showErrors: Helper.validateForm,
submitHandler: function (form) {
debugger;
Helper.httpPost("~/Login/ForgotPass",form, function (result) {
if (result.Status == 1) {
Helper.redirect("Login/Index");
}
else {
Helper.warning("Invalid Username or Password.");
// Helper.warning(result.Data);
}
})
}
});
})
can any one let me know how to do this.

"Authenticated" is not defined in my controller function in Angular. I am not sure what I am doing wrong. Running out of all the options.

In my Angular controller, "authenticated is not defined. I want to show the Update button only when the user is logged in. I am using ng-show when the user is logged in, otherwise hide the button. Can someone guide me what I am doing wrong?
JavaScript
$scope.signIn = function () {
$rootScope.auth.$login('password', {
email: $scope.email,
password: $scope.password
}).then(function (user) {
Materialize.toast('Logged in successfully', 1000);
console.log(authenticated);
$scope.authenticated = true;
}, function (error) {
if (error = 'INVALID_EMAIL') {
Materialize.toast('Email invalid or not signed up — trying to sign you up!', 5000);
$scope.signUp();
} else if (error = 'INVALID_PASSWORD') {
console.log('wrong password!');
Materialize.toast('Invalid password', 1000);
} else {
console.log(error);
}
});
};
$scope.loggedin = false;
Template
<div ng-if="loggedin">
<a class="btn waves-effect waves-red" ng-href="/#/editWelcome/{{welcome._id}}">Update
</a>
</div>
There is a typo:
console.log(authenticated);
maybe You wanted like this:
console.log('authenticated');
or maybe:
console.log(user);
because of authenticated variable does not exists, it does not move to next line to set $scope.authenticated = true;
You use <div ng-if="loggedin"> to toggle the Update link.
But in your controller, you never set the value of loggedin. Instead, you set $scope.authenticated = true;. I think you need to set $scope.loggedin = true;.
To answer the question with an example, you had multiple issues, the variable names are inconsistent, your console.log has an undefined object called authenticated,
$scope.authenticated = true; VS $scope.isLoggedIn = false.
You should use code below which sets the logged in at the controller and $rootScope. It includes getting yourself away from using $scope in the controller in favor of 'controller as vm', I suggest looking at http://www.johnpapa.net/angular-style-guide/
The code also provides a logging utility as this will help you with the logging error because you can add try/catch in the service.
Controller and Logging Utility JS
(function () {
var moduleId = 'app';
var controllerId = 'AngularController';
//define controller
angular
.module(moduleId)
.controller(controllerId, angularController);
angularController.$inject = ['$rootScope', 'logUtil'];
//Your controller code
function angularController($rootScope, logUtil) {
var vm = this;
vm.title = 'Your controller title';
vm.isLoggedIn = angular.isDefined($rootScope.isLoggedIn) ? $rootScope.isLoggedIn : false;
vm.signIn = signIn;
vm.signUp = signUp;
function signIn() {
$rootScope.auth.$login('password', {
email: $scope.email,
password: $scope.password
}).then(function (user) {
Materialize.toast('Logged in successfully', 1000);
logUtil.logDebug('authenticated');
vm.userId = user.id;
$rootScope.isLoggedIn = true;
vm.isLoggedIn = true;
}, function (error) {
$rootScope.isLoggedIn = false;
vm.isLoggedIn = false;
if (error === 'INVALID_EMAIL') {
logUtil.logDebug('no user');
Materialize.toast('Email invalid or not signed up — trying to sign you up!', 5000);
vm.signUp();
} else if (error === 'INVALID_PASSWORD') {
logUtil.logDebug('wrong password');
Materialize.toast('Invalid password', 1000);
} else {
logUtil.logError(error);
}
});
};
function signUp() {
//sign up function
}
activate();
function activate() {
logUtil.logDebug('Controller activated: ' + controllerId);
}
};
//logging utility constants
angular.module(moduleId).constant('logUtilConstants', {
LOG_ERROR_MESSAGES: true,
LOG_DEBUG_MESSAGES: true
});
//logging service
angular.module(moduleId).service('logUtil', logUtil);
logUtil.$inject = ['$log','logUtilConstants'];
function logUtil($log, logUtilConstants) {
var service = {
logError: function (logMessage) {
if (logUtilConstants.LOG_ERROR_MESSAGES) {
$log.error(logMessage);
}
},
logDebug: function () {
try {
if (logUtilConstants.LOG_DEBUG_MESSAGES) {
var args = Array.prototype.slice.call(arguments, 0);
var strArgs = args.join(' ');
$log.debug(strArgs);
}
} catch (e) {
console.log('log debug error', e);
}
}
}
return service;
}
})();
Controller Markup
<div ng-controller="AngularController as vm">
{{ vm.title }}
</div>
Conditional Div Markup
<div ng-if="vm.loggedin">
<a class="btn waves-effect waves-red" ng-href="/#/editWelcome/{{vm.userId}}">Update</a>
</div>

Posting to Popup Controller Before the Parent Page Controller

How do I force a popup page to post to its controller first before posting to the parent controller? The popup page is setting up some session variables that would be used in the parent page. When the user double click on the grid on the pop-up page, it goes directly to the parent controller instead of going to the child controller.
Here is the parent where the popup is being called
//Javascript to open the popup window
#using (Html.BeginForm("Student", "StudentPage", FormMethod.Get, new { onsubmit = "", id = "student" }))
{
//where the popup window is located
}
Here is the popup form:
#using (Html.BeginForm("Index", "StudentInformation", FormMethod.Post, new {id="StudentSearchForm"}))
{
#(Html
.Telerik()
.Grid((IEnumerable<OverrideStudent>)SessionWrapper.Student.OtherStudentSelected)
.Name("StudentData")
.DataKeys(Keys =>
{
Keys.Add(c => c.StudentID);
})
.DataBinding(databinding => databinding.Server())
.Columns(columns =>
{
columns.Bound(p => p.StudentId)
.Title("Student ID")
.Width(15)
.Sortable(true)
.Filterable(false);
columns.Bound(p => p.StudentDescription)
.Title("Description")
.Width(65)
.Sortable(true)
.Filterable(false);
columns.Command(command =>
{
command.Custom("AddStudent")
.Text("Select")
.DataRouteValues(routes =>
{
routes.Add(o => o.StudentID).RouteKey("StudentID");
routes.Add(o => o.StudentDescription).RouteKey("StudentDescription");
})
.Action("Student", "StudentInfo");
.HtmlAttributes(new { onclick = "PostData(this);StudentSelectClick(this)" });
}).Width(20);
}).ClientEvents(clients => clients
.OnComplete("OnComplete")
//.OnDataBinding("DataBinding")
//.OnDataBound("onRowDataBound")
.OnRowSelected("StudentDoubleClick")
)
.Sortable()
.Selectable()
.Filterable(filtering => filtering
.Enabled(true)
.Footer(true)
.HtmlAttributes(new { style = "padding-right: 0.0em;" }))
}
//This is the script that handles that double click:
function StudentDoubleClick(e) {
var fromCourse = "#SessionWrapper.Student.FromCoursePage";
var fromList = "#SessionWrapper.Student.FromListingPage";
if (fromCourse == "True") {
$('tr', this).live('dblclick', function () {
alert("Inside TR count = " + count);
count = count + 1;
DoSearchStudent(e);
});
}
if (fromList == "True") {
$('tr', this).live('dblclick', function () {
DoSearchStudent(e);
});
}
}
function DoSearchStudent(e) {
var row = e.row;
var StudentID = row.cells[0].innerHTML;
var StudentDescription = row.cells[1].innerHTML;
// alert(procCodeDesc);
var data = { "StudentID": StudentID, "StudentDescription": StudentDescription, "action": "Double Click" };
var url = '#Url.Action("Student", "StudentInfo")';
$.ajax({
url: url,
type: 'post',
dataType: 'text',
cache: false,
async: false,
data: data,
success: function (data) {
window.top.location.href = window.top.location.href;
},
error: function (error) {
alert("An error has occured and the window will not be closed.");
}
});
}
//This is the controller that I need to go to first
public class StudentInfoController : Controller
{
.......
public string Student(string StudentID, string StudentDescription, string action)
{
if (StudentDescription != null)
{
StudentDescription = HttpUtility.HtmlDecode(StudentDescription);
}
try
{
RedirectToAction("AddStudent", "StudentInfo", new { StudentID = StudentID, StudentDescription = StudentDescription, action = action });
}
catch (Exception e)
{
return "Error " + e.ToString();
}
return "Success";
}
}
After the double click, it goes directly to the controller below instead. AS a result, my variables are not being set resulting in null exception.
public class StudentPageController : Controller
{
.......
public string Student(string StudentID, string StudentDescription, Student Students)
{
...........
}
}
It was a timing issue. When the user close the popup window, the popup thread is not done executing. At the same time, another thread starts to run, and not all the session variables are set as of yet. Before closing the popup window, I added a 1 second delay.
setTimeout('StudentWindow.close()', 1000);

Categories