Is ok to deactivate a user account using GET http verb? - javascript

Im stuck with a simple but tricky task that im developing on ASP.NET MVC 5 web app.
I have a UserManager view wich i need to add a button to deactivate the account of the current logged user. So i have two options:
1) Create a input tag an hold the click event making a post using ajax:
<input type="button" id="deleteUser" value="Delete Account"/>
<script>
$('#deleteUser').click(function() {
$.post("#Url.Action("DeleteUser")",function() {
window.href.location = "#Url.Action("Home","Site")";
} );
});
</script>
On controller:
[HttpPost]
[Authorize]
public ActionResult DeleteUser()
{
//return json
}
2) Create a href and make a GET pointing to the DeleteUser action.
IMO these two options are correct, but the right thing to do is delete a user using the DELETE Http Verb, right? Since HTML5 doesnt support it, how to deal with it? In the options above, i prefer to use a href, because i can make a feedback easily based on the logic that i have, and i dont need to make a script for it.

Related

How can I access a JsonResult variable in my code behind file from the javascript of my view? Razor Pages. C#

Context: I am trying to pass a nested JSON object from my code behind page to a method in the .js in my view.
UI Flow: The user selects an organization from a ddl, then the ddl's onchange function is called, onchange function clicks the hidden submit button, code behind method is called which creates the nested json object with the needed organizational data.
Lessons Learned: I wasted too much time trying to make this happen via ajax. It is possible (maybe preferred) to use ajax to achieve my goal. If my page handler had been a get method, ajax would have been a quick solution. However, ajax in razor pages required a hidden field to contain the anti-forgery token for ajax posts. So why not use the razor page form to accomplish the same thing? This allows me to keep consistency throughout my application.
Notes: Please comment if there is a better way to do this. I used the form with the hidden submit button because it is what I could do quickly.
Solution:
Put ddl in a form.
<form asp-page-handler="DdlValueSelected">
<div class="form-group">
<label>Select Me</label>
<select class="form-control" onchange="ddlChanged()" asp-for="#Model.blah" asp-
items="#Model.blah">
</select>
</div>
<button hidden type="submit" id="ddlSubmitButton"></button>
</form>
Have the onchange method in your .js click the hidden submit button in the form.
function ddlChanged() {
$('#ddlSubmitButton').click();
}
3a. In your code behind method, make service call to return the object you need.
3b. Convert object to object type of JsonResult.
public async Task<IActionResult> OnPostDdlValueSelected(string ddlValue)
{
DataNeededAsJsonObject = await _service.GetDataNeededAsJsonObject(ddlValue);
ConvertedDataNeededAsJsonObject = new JsonResult(DataNeededAsJsonObject);
return Page();
}
Access your code behind variable of type JsonResult by using #Json.Serialize(object) in your .js in your view.
function getJsonData() {
jsonData = #Json.Serialize(Model.ConvertedDataNeededAsJsonObject);
console.log(jsonData);
}
I welcome feedback, so I can do it better next time.

Emit value on a search button depending on checkbox state, AngualrJS

My app has a Search Button, that hits an internal API with a GET Request. Then we fetch Data that are protected in some cases. I have a checkbox which is set to true by default to simulate the Back-End behavior.
If that box is unchecked then we add a parameter to our query GET Request protection: false. This tells the Back-End to give us access to unprotected Data.
My question is this. How to keep watch of the checkbox state in Angular Controller, and this change gets emitted to the search button?
I understand that I need to use $scope.watch for that, but AngularJS isn't my strong suit, so please help.
The protection parameter is passed as an Action from Redux, down to an RxJS Epic, to the Reducer and then injected to endpoint.js and service.js files that handle thoe requests.
That is done and working. My big problem is how to handle the angular part. Below you will find the code for the HTML and Controller files.
INDEX.HTML
<button class="btn btn-default btn-sm" ng-click="getData(something, protection)"
ng-disabled="Ctrl.loading">
Run Search
</button>
<span>Protection
<input type="checkbox" ng-model="Ctrl.Protection">
</span>
Controller.js
$scope.getData = (something, protection) => {
ctrl.getSomecData(protection, protection);
ctrl.saveRecentSearch(something);
};
So, one final go. I want to be able to check and uncheck the box, and that change should be emitted to the search button, and then inject that parameter in the GET Request.
Please help me do that in Angularjs. I haven't worked with it before this job, and it is really frustrating. Thanks for your time.
You just need to use ngChange directive of angular js on checkbox element.
method binded with ng-change attribute will called whenever checkbox is checked or unchecked.
further $watch is not recommended since it hits performance of the page.
Html:
<input type="checkbox" ng-model="Ctrl.Protection" ng-change="change()">
In your controller :
$scope.change = function() {
if(this.Protection){
//whatever you wish to do here
$scope.getData($scope.something, this.protection);
}
};

node.js & jade - making a post request and displaying the results in the same page without redirecting

I have node.js express web application which performs the CRUD operations on a button click. Here I need to update a record based on the input from the user. For this, I need to input the detail from the user, display the existing values of the record in the same page, and prompt the user whether he wants to change the data.
If yes, then I need to input the values from the user and update it. Is it possible to have this in a single jade file where I am getting the input values from user.
jade file :
extends ../layout
block content
.page-header
h3 Updation
form.form-horizontal(role='form', method='POST')
h4 Enter the employee id for which you want to update the details
input(type='hidden', name='_csrf', value=_csrf)
.form-group
label(class='col-sm-2 control-label', for='empid') Emp ID
.col-sm-2
input.form-control(type='text', name='empid', id='empid', autofocus=true)
.form-group
.col-sm-offset-2.col-sm-2
button.btn.btn-primary(type='submit')
i.fa.fa-pencil
| Get details
I have this file where I am getting the employee id from user and making the post request. I am not sure how to render the response to this same page itself and prompt for changing details.
Any help would be appreciated.
Yes, you can do this, but not with a form that gets submitted, because then your page is gone.
Instead, you can insert a button into your page that does an AJAX request to the backend, and on return of the AJAX request, you can dynamically replace some parts of your page with the returned data. Of course, you can include any data the user has entered into the AJAX request.
Since you want this all to happen in the frontend, you cannot do this in Jade. Instead, you need to add a script into your page that does what you want in the client's browser.
Here is an example of how to achieve this:
Put this in a file called ajax.jade:
mixin ajaxFunction
script.
function changeState(url, buttonid) {
$.ajax({url: url}).done(function (data) {
$('#' + buttonid).parent().html(data);
});
}
mixin ajaxButton(id, url, buttonLabel)
a.btn.btn-primary.btn-xs.btn-block(id='#{id}',
href='javascript:changeState(\'#{url}\', \'#{id}\')') #{buttonLabel}
Now you can put this mixin anywhere on your page. (Make sure the button id is unique across the whole page and does not contain spaces!). On click, it will replace itself with whatever the backend returned:
include ajax
+ajaxButton("myButton", "/some/url", "Klick me!")
Not sure if there's a way that the jade egine can partially render the jade template, If there is one way to do that, normally you can use Ajax to do this.
Form add submit event listener, in which you can set event.preventDefaut() to stop default submit process, in this way you can prevent page reloading.

edit user form angular

so here's my github for my recent project: https://github.com/ryanwaite28/form-site
its a form site where you can create and edit users. I got the create functionality working, however the edit isn't
when you click edit, i want to pass the user info into the edit function's parameters but i can't seem to get it right. i want to set the user's info to that of which is in the input box. is there something i'm doing wrong? Also, im using angular JS and jQuery.
You are not passing the user to the function in the html:
<td><button type="button" id="edit-btn" ng-click="editUser(user)">Edit</button></td>
Also, you need to reference the form of the "in edit" user somehow like:
$scope.editUser = function(user) {
$scope.userBeingEdited = user;
}
And reference the html of the edit form to this userBeingEdited part of the scope.
The saveChanges method should not be inside the edit function. Should be a separate function in which you can commit changes

Page changes when i submit the form

<form action="/devilmaycry/register?action=addtocart" method="post">
<input type="hidden" name="user" value="<%=user%>"/>
<input type="hidden" name="pid" value="<%=pid%>"/>
<input type="submit" value="Add to cart" onclick="add();"/>
</form>
i am using the above code to submit a form and add a product to cart
the java code it calls is as follows:
else if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==1)
{
pw.println("<h3>Added to cart !!!<h3>");
}
else
{
pw.println("<h3>Errror , try again <h3><br>");
}
it does add the product to the table but it changes the jsp page ... i tried to use requestDispatcher but the URL has many parameters so i want something else through which i can retain the same page and update the table also
In order to stay on the same page you need to use AJAX rather than submit the form in the traditional way. HTTP works in a request-response fashion, so when the user submits the form, the browser expects to receive a new page in the response from the server, and will thus refresh the page and render the new HTML it receives.
You have two options here:
Stick with the traditional HTTP form submission request-response approach, and when you receive the request on the server to add an item to the card, after you add the item to the card, rebuild the URL of the page that is showing the information to the user. In this case it is important to use the 'Redirect-After-Post' approach (i.e. in the response to the form POST you put a redirect to the page). Otherwise if the user refreshes the page by pressing F5, the form data will be resubmitted again and the item added again to the cart.
Go for an AJAX approach. In the add() function, you need to submit the form using Javascript. If you are using JQuery it makes it very easy for you to do this. There are various questions / examples if you search around, such as the one here.
In the latter case you will need to change a bit how you process the information from your Servlet but its the only way to get the browser to stay on the same page (without reloading it). You also have the success and error handlers, which you can use to show a message on the screen to display the result.

Categories