How handle event like click in RazorPages by C# functions - asp.net-core

I want to call a C# function when I click on a button, or select an item in selectList on the razor page.
In blazor , it is possible like this code:
<button class="btn btn-info form-control" #onclick="AddNewCategory" >Add New Category</button>
but in razor page, I can't use it
Please help me!

If you want to select an item in selectList on the razor page when clicking on a button,you can try to use js,here is a demo.When clicking the button,the selected value will be 4.
<select id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button onclick="changeSelectedItem()">test</button>
#section Scripts{
<script>
function changeSelectedItem() {
$("#select1").val(4);
}
</script>
}
And if you want to call a C# function when I click on a button,you can use ajax to call a handler.here is a demo:
cshtml:
#Html.AntiForgeryToken()
<button onclick="callHandler()">callHandler</button>
#section Scripts{
<script>
function callHandler() {
$.ajax({
type: "POST",
url: "?handler=TestHandler",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
//...
}
});
}
</script>
}
cshtml.cs:
public void OnPostTestHandler()
{
//do something here
}

Related

vue composition api cascading dropdown box

I wish to build a from using Vue composition api. And in the form, there would be two drop boxes. When first dropbox item selected, it will return the corresponding option in second dropbox? How could it be achieved in vue?
eg. When selected Avengers in team (first dropbox), it will display ["Captain America", "Iron Man", "Thor", "Hulk", "Black Widow", "Hawkeye"] option in second dropbox.
When selected JLA in team (first dropbox), it will display ["Superman", "Batman", "Wonder Woman", "Flash", "Green Lantern", "Aquaman"] option in second dropbox.
<div class="row mb-3">
<label class="col-sm-2 col-form-label">Favourite Team</label>
<select class="form-select" aria-label="Default select example" onchange="teamSelected(this.value)" name="team">
<option selected>Open this select menu</option>
<option value="Avengers">Avengers</option>
<option value="JLA">Justice League</option>
</select>
</div>
<div class="row mb-3">
<label class="col-sm-2 col-form-label">Favourite Hero</label>
<select class="form-select" aria-label="Default select example" id="superhero" disabled name="superhero">
</select>
</div>
<script>
import { ref } from 'vue';
export default {
name: 'App',
setup() {
const teamSelected = (event) => {
course.value = event.target.value;
};
return {
teamSelected,
};
},
};
</script>
Thanks in advance

Vue JS - Display option 2 of select menu after it is disabled

I am looking for help on how to display the second option in a select drop-down menu after the select menu is disabled.
It is disabled if there are fewer than 2 options left. The first option is the 'Please select' option but I would like it to display the one remaining option which is the second option. i.e. 'Scotland' in the code below. The data is pulled in using an Axios call so I do not know what the value will be.
Any help would be greatly appreciated.
The select menu code
<select disabled="disabled">
<option disabled="disabled" value="">Select nationality</option>
<option value="Scotland"> Scotland </option>
</select>
Vue
computed: {
selectDisabled: function() {
return this.options.length <= 2;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="quantity" :disabled="selectDisabled">
<option disabled value="">Select</option>
<option v-for="option in options" :value="option">{{option}}</option>
</select>
</div>
You need to create a special computed property that will dynamically tell the <select> which option it should show inside itself. <select> show the option that matches the <select>'s value.
So:
When the select is disabled (has less than 2 options) force it's value to be the value of the first listed option (this.options[0]).
When the select is enabled, pass the normal value selected by the user (this.value)
I've implemented the logic you need below (make sure to click "Run snippet"):
const App = {
el: '#app',
template: `
<div>
<!--
Remember that writing v-model="quantity" is the same as writing :value="quantity" #input="quantity = $event"
(or #input="quanity = $event.target.value" if you put in HTML elements)
You can't use v-model="valueFormatted" here because this would be the same as writing
:value="valueFormatted" #input="valueFormatted = $event.target.value"
So that's a mistake, because valueFormatted is a computed and you can't assign to it
(unless you create a special computed with a setter, but that's not what you need right now)
-->
<select :value="valueFormatted" #input="value = $event.target.value" :disabled="disabled">
<option disabled="disabled" value="">Select nationality</option>
<option v-for="option in options" :value="option">{{option}}</option>
</select>
<hr>
<div>
<button #click="options = ['Scotland']">Make the select have 1 item</button>
<button #click="options = ['Scotland', 'Poland']">Make the seelct have 2 items</button>
</div>
</div>
`,
data() {
return {
options: ["Scotland", "Poland"],
value: '',
}
},
computed: {
disabled() {
return this.options.length < 2
},
/*
* If this.disabled is true, returns the value of the first option
* If it's false, it returns the normal value from data (user selected)
*/
valueFormatted() {
//watch out - this computed will return undefined if this.disabled is true and if options is empty
//to avoid that, you can do for example this:
//return this.disabled === true ? (this.options[0] ?? '' ) : this.value;
return this.disabled === true ? this.options[0] : this.value;
},
},
}
new Vue(App);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<html>
<body>
<div id="app" />
</body>
</html>
You're probably going to use this select's value later to make eg. an API call, so make sure to send this.valueFormatted instead of this.value

Select is not populating via API call in VueJS

I'm very new to Vue and I'm doing Vue just because I need to use it in a project. Right now, I'm trying to populate a 'Select' by performing an API call. However, it is not working. Here's the code.
<template>
<form method="POST">
<label>
Website Name
</label>
<select name="website_id">
<option v-for="item in this.websiteData" :value="item.id">{{item.domain}}</option>
</select>
<input type="submit"/>
</form>
</template>
<script>
export default {
async beforeMount() {
await fetch('/api/get-website').then(res=>res.json()).then(data=>this.websiteData = data.map(item=>item));
console.log(this.websiteData);
},
// name: "FormComponent"
data(){
return {
websiteData: [],
postData: null
}
},
methods: {
}
}
</script>
<select name="website_id">
<option v-for="item in websiteData" :value="item.id">
{{item.domain}}
</option>
</select>
Typo in websiteData. In template you can access variables without this.

(change) not working with select2 in angular 5

The (change) directive is working fine with normal select html tag in angular 5. But if I implement select2 plugin, then (change) won't work.
Here is my html file
<select class="select2Select" [(ngModel)]="productSearchItem" (ngModelChange)="test()">
<option value="">Search entire store here...</option>
<option *ngFor="let product of products" value="{{ product.pid }}">{{ product.name }}</option>
</select>
Here is the function doing nothing just consoling something in typescript
test(){
console.log("Hi");
}
Script:
$(document).ready(function() {
$('.select2Select').select2();
});
Do the change event using jquery inside the lifecycle hook:
ngOnInit() {
$('.select2Select').on('select2:select', function (e) {
console.log("Hi");
});
}

Updating select box with Ajax, JavaScript and Webmatrix

I'm very new to Ajax.
What I'm trying to achieve, I would imagine, is fairly common. I have 2 dropdown boxes, referencing my database, these are called "area" and "resort". The idea is that when i choose and area from the first boxes, it ONLY shows resorts within that area in the second box.
Here is my form:
<div id ="homepage-form-div" class="row">
<form id ="homepage-form"action=" /Search1.cshtml">
<div class="span3">
<label>Area:</label>
<select name="area">
<option value="">Any</option>
#foreach(var row in qlistarea){
<option value="">#row.AreaName</option>
}
</select>
</div>
<div class="span3">
<label>Resort:</label>
<select name="resort">
<option value="">Any</option>
#foreach(var row in qlistresort){
<option value="">#row.ResortName</option>
}
</select>
</div>
<button type="submit" class="btn btn-default" value="Submit" style="p">Go!</button>
</form>
</div>
I thought it might be useful to see my current SQL code:
var listarea = "SELECT DISTINCT AreaName FROM ResortInfo";
var qlistarea = db.Query(listarea);
var listresort = "SELECT DISTINCT ResortName FROM ResortInfo";
var qlistresort = db.Query(listresort);
I'm guessing I'll need to somehow add a "+ WHERE AreaName = something" to the second query, dependant on the result of the AJAX call right?
Ok, you are using Razor syntax? Lets the show begin. And hey, arent you the same guy?
First I will tell you the basics of what I use.
I use the click keyup or change events.
I update the content of the body on ajax calls.
You need some basic tutorials buddy! Learn ASP.NET, then Learn jQuery Ajax! That will be simple.
My humble request to you:
Buddy please atleast once search for the code, before pasting it here. You will get alot of downvotes and might get blocked for posting more questions here. Please search for questions first. However this is the code.
Ok, to create the code:
I am going to post the code that works for me. Ok?
Here is the main page content:
#{
Layout = "~/_SiteLayout.cshtml";
}
<script>
$(document).ready(function () {
$('#area').change(function () {
$.ajax({
url: "testtworesult",
data: "type=resortupdate&resval=" + $('#area').val(),
success: function (data) {
$('#resort').html(data);
}
});
});
$('.btn').click(function () {
$.ajax({
url: "testtworesult",
data: "type=submit&area=" + $('#area').val() + "&res=" +
$('#resort').val(),
success: function (data) {
$('#result').html(data);
}
});
});
});
</script>
<div id ="homepage-form-div" class="row">
<div class="span3">
<label>Area:</label>
<select id="area">
<option value="">Any</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<div class="span3">
<label>Resort:</label>
<select id="resort">
<option value="">Any</option>
<option value="Love">Love</option>
<option value="Hate">Hate</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Submit" style="p">Go!</button>
<div style="font-weight: bold; margin-top: 20px;" id="result"></div>
</div>
Then the ajax page:
#{
var db = Database.Open("StayInFlorida");
var getresortval = Request.QueryString["resval"];
var type = Request.QueryString["type"];
var res = Request.QueryString["res"];
var area = Request.QueryString["area"];
var listresort = "SELECT DISTINCT ResortName FROM ResortInfo WHERE AreaName = '#0'";
var qlistresort = db.Query(listresort, getresortval);
if(type == "resortupdate") {
if(getresortval == "Kissimmee") {
Response.Write ("<option value='kissimmee'>Kissimmee</option");
}
if(getresortval == "Davenport") {
Response.Write("<option value='davenport'>Davenport</option");
}
} else if(type == "submit") {
Response.Write(#"You selected the Resort!<br>
Your area was: " + area + #".<br>
And your resort was: " + res + #". Hope you have a great trip!");
}
}
This won't save the content in Database, you will need to use INSERT INTO for that. Then you will require SELECT * FROM to select the data. I have simply used Response.Write().
Good luck.
For the AJAX call, you need a function AJAX can call which houses the Resort query after the user selects an Area. I'm not familiar with Razor or Webmatrix, so here's a pseudo-function (based on PHP) that you might be able to translate to your environment:
if (isset($_POST['area'])) set_resort(); /*AJAX will set $_POST['area'], then do function that returns output to AJAX*/
. . .
function set_resort() {
var listresort = "SELECT DISTINCT ResortName FROM ResortInfo WHERE AreaName = " $_POST['area']; /*make sure you escape that variable, however you do that in your syntax*/
var qlistresort = db.Query(listresort);
var resortArray = array(); /*or however you make arrays in your syntax*/
#foreach(var row in qlistresort){
resortArray[] = #row.ResortName; /*append each resort name to array*/
}
echo json_encode(#resortArray); /*JSON is preferred way to echo array back to AJAX*/
}
Your HTML would look like...
<div id ="homepage-form-div" class="row">
<form id ="homepage-form"action=" /Search1.cshtml">
<div class="span3">
<label>Area:</label>
<select id="areaSelect" name="area"> <!-- add an ID for easier jQuery selection -->
<option value="">Any</option>
#foreach(var row in qlistarea){
<option value="">#row.AreaName</option>
}
</select>
</div>
<div class="span3">
<label>Resort:</label>
<select id="resortSelect" name="resort"> <!-- add an ID for easier jQuery selection -->
<option value="">Any</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Submit" style="p">Go!</button>
</form>
</div>
Finally, your jQuery AJAX call would be like:
$('#areaSelect').on('change', function() {
var str = $(this).serialize();
$.ajax({
type: 'POST',
url: /*URL of your page*/
dataType: 'json',
data: str,
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown + '\n' + textStatus);
},
success: function(msg) {
$.each(msg, function(index, value) {
$('#resortSelect').append('<option value=' + index + '>' + value + '</option>'; /*add each resort from the set_resort() query to the resort select input*/
});
});
});