Calling C# Function from ASP.NET View [duplicate] - javascript

This question already has answers here:
How to call a C# function from JavaScript?
(7 answers)
How to Call Controller Actions using JQuery in ASP.NET MVC
(5 answers)
Closed 4 years ago.
I have an ASP.Net Entity Framework view where I have multiple drop-down lists. Once a user changes an item in this list, I need to call a c# method which is passed the values in all of the dropdown lists to check whether their values overlap.
Currently I have:
#Html.DropDownListFor(model => model.Periods[i].StartTime, new SelectList(Model.DateTimeList, Model.Periods[i].StartTime), new {#class = "form-control", onchange = "dropdownChange()" })
which called a method called dropdownChange():
<script>
function dropdownChange() {
#{
var overlapping = PeriodController.ConfigureViewModel.IsOverLapping(Model);
}
console.log("here");
}
</script>
This method is found by the view but doesn't go into my c# code as I have tested by putting in javascript code and it is run. e.g. the console.log appears but doesnt call the c# code.
Either a solution to this or a more sophisticated way to call a c# method every time a dropdownlist is changed.
Added Ajax Method:
$.ajax({
type: "POST",
data: { 'Model': Model },
success: function(isOverLapping) {
overLappping = isOverLapping;
console.log(1);
},
error: function() {
console.log(2);
}
});

One line answer: MVC doesn't work like that.
Longer answer: You can't access the server-side code directly from the browser like that. The most common solution is to use something called AJAX to call the C# function on the server. You then need to write code in the View to handle the response from the server. Have a look at this question and this answer: https://stackoverflow.com/a/16186212/5173105

Related

Is it good practice to use razor pages directives inside javascript <script> tags to pass model property values?

I'm developing a web app using asp.net core MVC and I've found my self using razor pages directives to pass model property values to javascript for further manipulation of the page. Is this ok? Should I worry of security concerns? If so, could some one explain?
Thanks in advance for any clarification.
Is it good practice to use razor pages directives inside javascript tags to pass model property values
Yes.When you use js to call razor page handler,it is sending a request to razor page handler in js,and getting the response of it.So it is safe.
Here is a demo using ajax to get data from handler:
function Test() {
$.ajax({
url: '?handler=Test',
type: 'GET',
success: function (data) {
//getting data here
},
error: function (result) {
}
});
}
handler:
public xxx OnGetTest(){
//return data here
}
It is okay to pass data in javascript for manipulation in your Razor pages. But if you're passing some sensitive information like (ID, password, email, etc.) then make sure to encrypt it. Because anyone can easily find this information in the browser's console if it is passing through Javascript

How to declare variable outside of callback, modify it in the callback, then use modified value outside? [duplicate]

This question already has answers here:
Javascript - Stop form submit depending on ajax response [duplicate]
(2 answers)
jQuery preventDefault() not working inside AJAX call
(6 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I'm looking for a way to modify a variable declared outside of a callback, then use the modified variable after defining the callback. My intent is reflected in the code:
$('#my_form').submit(function() {
let my_condition
let data = $(this).serialize()
$.ajax({
method: 'POST',
url: '/my_url',
data: data
})
.done(function(json_response) {
if (json_response.my_variable) {
my_condition = true
}
else {
my_condition = false
}
})
// I'm looking for a way to guarantee `my_condition` is set by the AJAX before the below code is run.
if (my_condition) { // I know `my_condition` will be null because this line won't wait for the AJAX to finish and set `my_condition`.
return true
}
else { // The event handler will always hit this condition.
return false
}
})
I'm aware that I could add blocking sleep time before checking my_condition to wait for the AJAX. This is not a solution I'm looking for. I'm also aware that I could set my_condition based on inspecting data on the frontend. However, for reasons specific to my use case, data needs to be processed on the backend. Lastly, I want to avoid the AJAX setting async: false.
I know why the code above does not work. My question is, is there some way to achieve the desired result? I have a feeling there might be a solution that uses Promise, but I don't see exactly how that would be done.
Edit 1: The specific use case is with regards to form submission. I want the submit handler to return true or false, i.e., submit via the form's action attribute (when my_condition is true) or a different (AJAX) route (when my_condition is false) based on backend processing results of data.
Edit 2: This is indeed a duplicate of Javascript - Stop form submit depending on ajax response [duplicate]
I suspect (although specific problem is not clear) you want the form to submit only if you get a valid response in the ajax.
You can prevent the initial submit and then submit the form inside the done callback if condition is met.
$('#my_form').submit(function(e) {
// prevent submit
e.preventDefault()
let form = this;
let data = $(form).serialize()
$.ajax({
method: 'POST',
url: '/my_url',
data: data
})
.done(function(json_response) {
if (json_response.my_variable) {
// trigger native submit, will bypass this jQuery submit listener
form.submit()
}
else {
// do something else
}
})
})

How to call a DAO method through a javascript function? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
I'm writing a jquery code and calling a JavaScript function through it on a jsp page.
This is the jquery function
$(function () {
$('#defaultCountdown').countdown({until: $.countdown('//SomeTime'),onExpiry: liftOff});
});
liftOff is a javascript method which is called after the specified time expires.
This is the JavaScript function
<script>
function liftOff() {
alert("Before Delete");
<% DAO_Object.deleteRecord(ID);%>
alert("After Delete");
}
</script>
Now here the problem is, the line <% DAO_Object.deleteRecord(ID);%> is getting executed before the function call and the record from database is getting deleted. The alert statements are executing correctly AFTER the function call.
Am i calling the deleteRecord method incorrectly?
You are mixing your server-side JSP logic with your client-side JavaScript logic.
Everything between <% %> runs on your servlet when it's processing the request, so the record is already deleted by the time you get the response in the browser. If you look at the HTML/JS you are receiving in the browser using Chrome DevTools or similar tool, you will see that there is nothing between those alert(...) calls.
Your solution here is to setup a route that handles the deleteRecord() on the server-side, and call it via AJAX in your liftOff() method. So liftOff() would look something like this:
// assuming `id` is a string here
function liftOff(id) {
alert("Before Delete");
// You'll have to setup this endpoint to run
// your `DAO_Object.deleteRecord(ID);` code
// in your JSP code.
$.get("/delete/my/record/" + id, {
error: function(e){
// some kind of error occurred in making the request
},
success: function(resp){
// `resp` is the response from the server
alert("After Delete");
}
});
}

How to call a PHP function with parameter call with OnClick event? [duplicate]

This question already has answers here:
How to call a PHP function on the click of a button
(13 answers)
Closed 7 years ago.
I need to call a PHP function as simply as possible with OnClick event:
<button onclick="Function(5)">Call PHP function</button>
I searched for the answer, but could not find it. I think I have to use AJAX or something, but I have no experience with it. Please give me an example as simple as possible on how to call a PHP function with parameter using OnClick event.
I wouldn't use inline events on html elements - it becomes a bit of a mess. You are going to need to use Ajax to get this done. Firstly i would set up your php function in it's own page/action then set up your javascript/jquery request event like so.
<button class="call-php" value="click me"/>
$('.call-php').click(function(){
$.ajax({
async: false,
url : '/myphp.php',
type : 'get',
data : {},
success:function(data) {
// do something
},
});
});
You can call like this
<?php Function(5)?>)

Model save success callback is not fired [duplicate]

This question already has an answer here:
Model save backbone
(1 answer)
Closed 8 years ago.
I have a modal view which has a form. When I try to save the model, a REST call is made and I need to close the modal view after that..
self.myModel.url = "api/myClass/";
self.myModel.save({
success: function() {
self.trigger("afterSave");
self.removeModal();
}
}).fail(function() {
$('#save', self.el).button('reset');
});
Now my REST API code is executed fine...I have debugged on the last return statement from REST resource..
But my JS code does not go inside the success callback function.
Am I doing something wrong with the JS syntax?
So here is your problem:
self.myModel.save({
success: function() {
self.trigger("afterSave");
self.removeModal();
}
})
.save() method expects the first parameter to be the data. And the second object should contain options.
If you don't have any data to pass, you should modify the above call to this:
self.myModel.save({},{
success: function() {
self.trigger("afterSave");
self.removeModal();
}
});
You should be all set this way! Suggest you to check the documentation : Backbone Docs
the first param for save() should be the model data and the second is the callbacks
self.myModel.url = "api/myClass/";
self.myModel.save({
"name":"Bob"
},{
success: function() {
self.trigger("afterSave");
self.removeModal();
}
}).fail(function() {
$('#save', self.el).button('reset');
});

Categories

Resources