How to I call 2 variables in Vuejs? - c#

I am using Vuejs.
And I want to call 2 variables.
How should I do?
These are my real codes.
(I want to add a codes that will hide the (x) button in a modal with a class [.close])
I edited my previous post. Sorry 'bout that.
window.app = new Vue({
el: '#vuelayoutdiv',
data: {
text: null
},
methods: {
submitToSignIn: function () {
window.location.href = "/{Contoller}/{Index}"
},
checkEmail: function (e) {
if (this.text) {
return true;
};
if (!this.text) {
this.$bvModal.show('emailmodal');
}
}
}
});
<b-modal id="emailmodal" hide-footer>
#*<template v-slot:modal-title>
Using
<code>$bvModal</code> Methods
</template>*#
<div class="d-block text-center">
<h3 style="text-align:left">Email required.</h3>
</div>
<b-button class="mt-3" block v-on:click="$bvModal.hide('emailmodal')">Close Me</b-button>
</b-modal>
<b-nav-item class="navbarsigntext signin" v-on:click="submitToSignIn">SIGN IN</b-nav-item>

It's easy to access other Vue instances variables. Although this isn't really common practice, and I'm not really sure what you are trying to do.
Here is an example, where there is thre instances in total, where the third, gets the message variable from object one and two.
var vueObj1 = new Vue({
data () {
return {
message: "vueobj1"
}
},
})
var vueObj2 = new Vue({
data () {
return {
message: "vueobj2"
}
},
})
var vueObj3 = new Vue({
el: '#app',
computed: {
messageFromOtherInstances () {
return vueObj1.message + ' ' + vueObj2.message
}
}
})
I've a small codepen for you, to play with: https://codepen.io/dasmikko/pen/XWWybdr

Use data as a function and return your variables.
Read the syntax in Vue js : - https://v2.vuejs.org/v2/guide/components.html
var variable1 = new Vue({
el: '#app1',
data () {
return {
text1:"sample"
}
},
})
var variable2 = new Vue({
el: '#app2',
data () {
return {
text2:"sample"
}
}
})
<script src="https://unpkg.com/vue#2.5.9/dist/vue.js"></script>
<div id="app1">
{{ text1 }}
</div>
<div id="app2">
{{ text2 }}
</div>

Related

asp.net Razor Pages - Update select list based on the selection of another select list

I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to integrate stripe payment with custom form in ASP.NET MVC? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How do I use custom stripe form and then integration with 3D Security options using ASP.NET MVC?
Custom Form Design using Razor/ Html
<div class="campagin_start content" style="max-width:100%">
<div class="cell example example2" id="">
<form>
<div class="row">
<div class="field">
<div id="example2-card-number" class="input empty"></div>
<label for="example2-card-number" data-tid="elements_examples.form.card_number_label">Card number</label>
<div class="baseline"></div>
</div>
</div>
<div class="row">
<div class="field half-width">
<div id="example2-card-expiry" class="input empty"></div>
<label for="example2-card-expiry" data-tid="elements_examples.form.card_expiry_label">Expiration</label>
<div class="baseline"></div>
</div>
<div class="field half-width">
<div id="example2-card-cvc" class="input empty"></div>
<label for="example2-card-cvc" data-tid="elements_examples.form.card_cvc_label">CVC</label>
<div class="baseline"></div>
</div>
</div>
<button id="card-button">#WebResources.Donate $#Model.budget</button>
Cancel
</form>
<p id="payment-result"><!-- we'll pass the response from the server here --></p>
</div>
</div>
Script
var stripe = Stripe('#ViewBag.StripePublishKey');
var elementStyles = {
base: {
color: '#32325D',
fontWeight: 500,
fontFamily: 'Source Code Pro, Consolas, Menlo, monospace',
fontSize: '16px',
fontSmoothing: 'antialiased',
'::placeholder': {
color: '#CFD7DF',
},
':-webkit-autofill': {
color: '#e39f48',
},
},
invalid: {
color: '#E25950',
'::placeholder': {
color: '#FFCCA5',
},
},
};
var elementClasses = {
focus: 'focused',
empty: 'empty',
invalid: 'invalid',
};
var elements = stripe.elements({
fonts: [
{
cssSrc: 'https://fonts.googleapis.com/css?family=Source+Code+Pro',
},
],
// Stripe's examples are localized to specific languages, but if
// you wish to have Elements automatically detect your user's locale,
// use `locale: 'auto'` instead.
locale: window.__exampleLocale
});
var Id = #Html.Raw(Json.Encode(Model.Id)); // Get Id From Model
var cardNumber = elements.create('cardNumber', {
showIcon: true,
style: elementStyles,
classes: elementClasses,
});
cardNumber.mount('#example2-card-number');
var cardExpiry = elements.create('cardExpiry', {
style: elementStyles,
classes: elementClasses,
});
cardExpiry.mount('#example2-card-expiry');
var cardCvc = elements.create('cardCvc', {
style: elementStyles,
classes: elementClasses,
});
cardCvc.mount('#example2-card-cvc');
var formClass = '.example2';
var example = document.querySelector(formClass);
var form = example.querySelector('form');
var resultContainer = document.getElementById('payment-result');
// Payment Button Handle
form.addEventListener('submit', function (event) {
$('#AjaxLoader').show();
event.preventDefault();
resultContainer.textContent = "";
stripe.createPaymentMethod({
type: 'card',
card: cardNumber,
}).then(handlePaymentMethodResult);
});
function handlePaymentMethodResult(result) {
if (result.error) {
$('#AjaxLoader').hide();
$("#canceltran").show();
// An error happened when collecting card details, show it in the payment form
resultContainer.textContent = result.error.message;
} else {
// Otherwise send paymentMethod.id to your server
fetch('/cart/pay', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ PaymentMethodId: result.paymentMethod.id, Id: Id})
}).then(function (result) {
return result.json();
}).then(handleServerResponse);
}
}
function handleServerResponse(responseJson) {
if (responseJson.error) {
// An error happened when charging the card, show it in the payment form
resultContainer.textContent = responseJson.error;
$('#AjaxLoader').hide();
$("#canceltran").show();
} else if (responseJson.requiresAction) {
// Use Stripe.js to handle required card action
stripe.handleCardAction(
responseJson.clientSecret
).then(function (result) {
if (result.error) {
$('#AjaxLoader').hide();
resultContainer.textContent = result.error.message;
$("#canceltran").show();
// Show `result.error.message` in payment form
} else {
// The card action has been handled
// The PaymentIntent can be confirmed again on the server
fetch('/cart/pay', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ PaymentIntentId: result.paymentIntent.id, Id:Id })
}).then(function (confirmResult) {
return confirmResult.json();
}).then(handleServerResponse);
$('#AjaxLoader').hide();
}
});
}
else {
// Show a success message or Required action
}
}
Controller -In Constructor, you have to use your Stripe Credentials
public class CartController : ControllerBase
{
public CartController()
{
StripeConfiguration.ApiKey = YOUR API KEY; // Replace your API KEY here
}
string stripePublishKey = YOUR PUBLISHER KEY; // Replace your PUBLISHER KEY here
private class StripeDataReq
{
public string PaymentMethodId { get; set; }
public string PaymentIntentId { get; set; }
public string Id { get; set; }
}
public async Task<ActionResult> Pay(StripeDataReq stripeDataReq)
{
// From Id you can get the value
var cart = await Cart.Table.LookupAsync(stripeDataReq.Id);
// We set amount (amout*100) because here amount consider in cent (100 cent charge $1) so
var amount = cart.Budget * 100;
var email = ""; // Set Email Id for payment Receiver
var service = new PaymentIntentService();
PaymentIntent paymentIntent = null;
try
{
if (stripeDataReq.PaymentMethodId != null)
{
// Create the PaymentIntent
var options = new PaymentIntentCreateOptions
{
Description = cart.Desc,
PaymentMethod = stripeDataReq.PaymentMethodId,
//Shipping is not nessasery for every region this is useful for an Indian Standard
//Shipping = new ChargeShippingOptions
//{
// Name = giver.Name,
// Address = new AddressOptions
// {
// Line1 = "510 Townsend St",
// PostalCode = "98140",
// City = "San Francisco",
// State = "CA",
// Country = "US",
// },
//},
ReceiptEmail = email,
Amount = amount,
Currency = "usd",
Confirm = true,
//ErrorOnRequiresAction = true,
ConfirmationMethod = "manual",
};
paymentIntent = service.Create(options);
}
if (stripeDataReq.PaymentIntentId != null)
{
var confirmOptions = new PaymentIntentConfirmOptions { };
paymentIntent = service.Confirm(
stripeDataReq.PaymentIntentId,
confirmOptions
);
}
}
// StripeException handle all types of failure error and then return the message into FE
catch (StripeException e)
{
return Json(new { error = e.StripeError.Message });
}
TempData["Id"] = stripeDataReq.Id;
return await generatePaymentResponse(paymentIntent);
}
//For 3D secure card
private async Task<ActionResult> generatePaymentResponse(PaymentIntent intent)
{
var CartId = TempData["Id"];
if (intent.Status.ToString().ToLower() == "succeeded")
{
// Handle post-payment fulfillment
return Json(new { success = true });
}
// requires_action means 3d secure card required more authentications for payment
else if (intent.Status == "requires_action")
{
// Tell the client to handle the action
return Json(new
{
requiresAction = true,
clientSecret = intent.ClientSecret
});
}
else
{
// Any other status would be unexpected, so error
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid PaymentIntent status");
}
}
}
Here is my working code with custom form integration using stripe payment, hope this post will help many developers

The view doesn't return from controller

I want to carry data by onclick function to the next page. All data is carried along with by giving parameter but it doesn't return View from the controller. Please help me. I'm stuck in here two days this is my school project.
OnClick button:
<div class="row">
<div class="col-sm-4"></div>
<button class='btn bg-blue next' onclick="checkamt(#Model.TotalAmt)">Next</button>
</div>
Controller:
public ActionResult ComfirmPay(int e = 0, string TaxType = null, int CurrentAmt = 0)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View("ComfirmPay");
}
Ajax:
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
alert('bad');
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
alert('good');
$.ajax({
cache: false,
url: '#Url.Action("ComfirmPay", "Home")',
data: { e: e, taxtype: taxtype, currentamt: currentamt },
beforeSend: function () {
},
success: function () {
},
complete: function () {
}
})
}
}
View:
<div class="col-md-9 col-xs-9">
<p class="text-muted">You have total <b class="text-green">#ViewBag.CurrentAmt</b> points</p>
</div>
Remove the ajax function and do this
window.location.href = "#Url.Action("ComfirmPay", "Home")" + "?e=" + e + "&taxtype=" + taxtype + "&currentamt=" + currentamt
The comment on this post explains a little more about why what you are trying to do does not work.
i think for your purpose there is no need of ajax call. you can use window.location.hrefas follows
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
window.location.href = '/Home/ComfirmPay?e='+e+'&taxtype='+taxtype+'&currentamt='+currentamt;
}
}
and in the controller
public ActionResult ComfirmPay(string e, string TaxType, string CurrentAmt)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View();
}

How to create Vue.Js component dynamically - modal messagebox

I am working in asp.net project with VueJs. I would like to create own message box depends on modal. My problem is to with each $emit call create component, show message box and in hideModal function destroy component.
Actually, when I will call many times in for loop this.$root.$emit('show-message', this.showMessage); - component shows just one time. I want to show every messageBox, not only the first one.
(function() {
'use strict'
Vue.component('message-box', {
props: {},
data: function() {
return {
messageTitle: '',
messageBody: '',
visible: false,
}
},
template: `<b-modal centered v-model="visible">
<template slot="modal-header">
{{messageTitle}}
</template>
<div class="d-block text-center">
{{messageBody}}
</div>
<template slot="modal-footer">
<b-button class="mt-3" variant="outline-info" block v-on:click="hideModal()">Ok</b-button>
</template>
</b-modal>`,
created: function() {
this.$root.$on('show-message', this.showMessage)
},
beforeDestroy: function() {
EventBus.$off('show-message', this.showMessage)
},
methods: {
showModal() {
this.visible = true
},
hideModal() {
this.visible = false
},
close: function(index) {
this.alerts.splice(index, 1)
},
showMessage: function(title, message) {
this.messageTitle = title
this.messageBody = message
this.showModal()
},
},
})
})()
Admittedly, this is not exactly the solution I was looking for. Still, it solves my problem.
(function () {
'use strict';
Vue.component('message-box', {
props: {
},
data: function () {
return {
messages: [],
actualMessage: {},
visible: false
};
},
template:
`<b-modal centered v-model="visible">
<template slot="modal-header" v-if="actualMessage">
{{actualMessage.messageTitle}}
</template>
<div class="d-block text-center" v-if="actualMessage">
{{actualMessage.messageBody}}
</div>
<template slot="modal-footer">
<b-button class="mt-3" variant="outline-info" block v-on:click="hideModal()">Ok</b-button>
</template>
</b-modal>`,
created: function () {
this.$root.$on('show-message', this.showMessage);
},
beforeDestroy: function () {
EventBus.$off('show-message', this.showMessage);
},
methods: {
showModal() {
this.actualMessage = this.messages[0];
this.visible = true;
},
hideModal() {
this.visible = false;
this.messages.splice(0, 1);
if (this.messages.length > 0) {
var vm = this;
setTimeout(function () { vm.showModal(); }, 500);
}
},
showMessage: function (title, message) {
this.messages.push({ messageTitle: title, messageBody: message });
if (!this.visible)
this.showModal();
}
}
});
})();

Jquery Autocomplete + ASP.NET MVC 3 not displaying the results

My View Code:
Script and Css:
<link href="#Url.Content("~/Content/jquery-ui-1.8.18.custom.css")" rel="stylesheet"type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.18.custom.min.js")" type="text/javascript"></script>
Input text:
#Html.TextBoxFor(model => model.Filter.HouseName, new { style = "width: 205px", onKeyUp = "updateHouseNames()" })
Javascript:
function updateHouseNames() {
var houseArray = new Array();
$.post('#Url.Action("LoadHouses")', { houseName: $("#Filter_HouseName").val() }, function(houses) {
houseArray = houses;
});
$("#Filter_HouseName").autocomplete({
source: houseArray
});
}
Controller method:
[HttpPost]
public JsonResult LoadHouses(string houseName)
{
var houses = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
return Json(houses);
}
I debug the javascript and the houses are selected.. but the results are not displayed in autocomplete. Why?
I don't really think you should be doing it this way. If you need to customize the logic then use a callback on the autocomplete method:
$(function () {
$('#Filter_HouseName').autocomplete({
minLength: 1,
source: function (request, response) {
var term = request.term;
var houseArray = new Array();
$.post('#Url.Action("LoadHouses")', { houseName: term }, function(houses) {
houseArray = houses;
response(houseArray);
});
}
});
});

Categories