Bootstrap Alerts in Asp.net Core Razor Pages - asp.net-core

How to configure bootstrap alerts in asp.net core razor pages.
<div class="alert alert-success">
<strong>Well done!</strong> You successfully read this important alert message.
</div>

As far as I know, if you want to show the alert, you could try to use jquery to achieve your requirement, you could add class in into the alert div. You could use ajax to call the razor page's onpost method and check the response if the response is true then you could alert success if not you could alert fail message.
More details, you could refer to below example codes:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
#{
Layout = null;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="alert alert-success alert-dismissible fade" id="buttonAlertSuccess">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
<div class="alert alert-success alert-dismissible fade" id="buttonAlertFail">
<strong>False</strong> You failed read this important alert message.
</div>
<button class="btn btn-secondary" id="modalButton" type="submit">Button</button>
#Html.AntiForgeryToken()
<script>
$(function () {
$("#modalButton").click(function () {
$.ajax({
type: "post",
url: "index",
beforeSend: function (xhr) {
xhr.setRequestHeader("CSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
if (response == "True") {
$("#buttonAlertSuccess").addClass('in');
} else {
$("#buttonAlertFail").addClass('in');
}
}
});
})
});
</script>
Post method:
public ActionResult OnPost() {
return new JsonResult("True");
}
Notice:
If you want to use ajax call ,you should set the CSRF-TOKEN settings in the startup.cs ConfigureServices method like below:
services.AddAntiforgery(o => o.HeaderName = "CSRF-TOKEN");
Result:

Please find the complete code and try if it helps
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert-success">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
</body>
</html>

Related

Failing to send Email (Mailtrap) with Laravel 9 , by getting data from Vue.js 3 component , with Axios

Hello when i get some data on my Vue app (from 2 forms, 1 select and 1 table), i want to click a button to send that data to the email put on the respective form. With my code, i am able to show the data i want to send, in a output i create on my app, as testing, however no mail is sent. My .env file is filled correctly and here are my other files
I created a mailable ComprasMail
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class ComprasMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$subject = 'Compra Efectuada com Sucesso';
return $this->view('Email.comprasMail')->subject($subject);
}
}
I created a blade file por my mail template
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Material+Icons"rel="stylesheet">
<link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png">
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<!-- Site CSS -->
<link rel="stylesheet" href="/css/style.css">
<!-- ALL VERSION CSS -->
<link rel="stylesheet" href="/css/versions.css">
<!-- Responsive CSS -->
<link rel="stylesheet" href="/css/responsive.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/custom.css">
<link rel=”stylesheet” href=”https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css”>
<!-- Modernizer for Portfolio -->
<script src="/js/modernizer.js"></script>
</head>
<body>
<tr>
<div id="hosting" class="section wb" style="background: rgb(248, 248, 248)">
<br>
<br>
<table cellpadding="0" height="100" width="100%">
<tr>
<td text-align="center" valign="top" class="email-container">
<div>
<td text-align='center' style='text-align:center'><a href="http://127.0.0.1:8000/home" target="_blank">
</div>
<br>
<div class="row dev-list ">
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 wow fadeIn" data-wow-duration="1s" data-wow-delay="0.3s">
<div class="wow fadeIn" text-align="center" style="background-color: rgba(0, 0, 0, 0.10); border-radius: 15px;" data-wow-duration="1s" data-wow-delay="0.3s">
<br>
<div class="message-box">
<div class="widget-title">
<h3 style="color: #E62B36; font-family: Eczar;"><strong>Bom dia caro {{$data['nome']}}</strong></h3>
<h4 text-align="center"> {{$data['transportadora']}} </h4>
</div>
<!-- end title -->
</div>
<hr>
<h6 text-align="center"> © {{ date('Y') }} Desafio Tecnico. Todos os Direitos Reservados</h6>
<br>
<br>
</div>
<!--widget -->
<br>
</div><!-- end col -->
</div><!-- end row -->
</tr>
</table>
</div><!-- end container -->
Here is my route
Route::post('/mail-send', [ProdutoController::class, 'mailSend']);
In my controller ( when i tried the return response that is commented, i simply have a 500 error)
public function mailSend(Request $request) {
return response()->json([$request->all()]);
$email = $request->email;
$data = [
'name' => $request->nome,
'transportadora' => $request->transportadora
];
Mail::to($email)->send(new ComprasMail($data));
/* return response()->json([
'message' => 'Mail has sent.'
], Response::HTTP_OK);*/
}
In my vue component, first the button
<button :disabled="isDisabled2" #click="sentMail"> Add </button>
my data()
data() {
return{
compras:[],
nome:"",
email:"",
transportadora:"",
output:"",
My sentMail function
sentMail(e) {
e.preventDefault();
var obj = this;
axios.post('/mail-send', {
nome: this.nome,
email: this.email,
transportadora: this.transportadora,
compras: this.compras
}).then(function (response) {
obj.output = response.data;
})
.catch(function (error) {
obj.output = error;
});
},
With this , as i said, all the data i want to collect is correctly saved, and appear how it is expected when i call the obj.output. However i am not able to send any email . First i am trying to send emails with only the name, to see if it works, then after that i will put more on the template.
Thank you in advance
Edit: Just did this tutorial as a way to test if i at least could send a simple email and it worked, so at least i know now my problem it is not with the config with Mailtrap and it is somewhere inside my code
https://www.youtube.com/watch?v=WU4_HzTa6PM
Edit 2: Made some changes on the code,but still won't work. After some testing i concluded that my Mailable, and config are correct, since with the small tutorial i used for testing, it worked, however i am not understanding why the mail i set up isn't being sent
I would appreciate any kind of help. Thank You
Just more update. The error that is giving me on the console is:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
settle.js:19 Uncaught (in promise)
AxiosError
code
:
"ERR_BAD_RESPONSE"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 500"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: {…}, status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
stack
:
"AxiosError: Request failed with status code 500\n at settle (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=600aa94f:1116:12)\n at XMLHttpRequest.onloadend (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=600aa94f:1327:7)"
[[Prototype]]
:
Error
After several time looking dor a solution to my problem, i finally was able to find one. In my Script i simply needed to change error to error.response.data For some reason, with only «error» it was always giving a 500 error
sentMail(e) {
e.preventDefault();
var obj = this;
axios.post('/mail-send', {
nome: this.nome,
mail: this.email,
transportadora: this.transportadora,
compras: this.compras
}).then(function (response) {
obj.output = response.data;
})
.catch(function (error) {
obj.output = error;
});
},

How to make this ASP.NET Core Model Validation work on client-side?

In my ASP.NET Core 1.1.1 app the following Model Validation is not working. I think the issue is related to me not properly adding validation scripts in Main View below.
Scenario:
I click on a button on Main View that calls a partial view.
I enter all correct values, in partial view and submit the form (in partial view), the form successfully gets submitted and all the values are correctly entered into SQL server db.
I then intentionally enter a string, say, abc into the input box for price (that is of nullable type float) and submit the form. A client side error does NOT show up even (the javascript is enabled on my Chrome browser). Hence, Form gets submitted to the server where ModeState.IsValid, as expected, is false in the POST action method.
Question: Why client-side validation (as shown in step 3) above is not working and how we can make it work?
Note: All the css and javascripts were added and configured by default by VS2017 when the project was created. So I think scripts are all there and I may not be calling them correctly on the views - but that's just an assumption.
MyViewModel
public class MyViewModel
{
public int FY { get; set; }
public byte OrderType { get; set; }
public float? Price { get; set; }
....
}
Main View
#model MyProj.Models.MainViewModel
...
<div>
<button type="submit" name="submit"...>GO</button>
</div
#section scripts
{
<script>
$(document).ready(function () {
....
$('.tab-content').on('click', '.BtnGO', function (event) {
....
$.ajax({
url: '#Url.Action("SU_AddCustOrder", "MyContr")',
data: { ....},
contentType: 'application/json',
dataType: 'html',
type: 'GET',
cache: false,
success: function (data) {
if (BtnVal == 'AddOrderBtnGo')
$('#menuAP').html(data);
else if ....
error: function (....){
alert(...);
}
});
});
MyContrController:
[HttpGet]
public IActionResult AddCustOrder(int Order_id)
{
....
return PartialView("~/Views/PartialsV/MyPartialView.cshtml", myVM);
....
}
[HttpPost]
public IActionResult AddCustOrder(MyViewModel model)
{
....
if(ModelState.IsValid)
{
....
}
....
}
Partial View
....
<div class="form-group">
<label asp-for="Price"></label>
<div class="col-md-10">
<input asp-for="Price" class="form-control"></input>
<span asp-validation-for="Price" class="text-danger"></span>
</div>
</div>
....
<button type="submit" name="submit"...>Add Order</button>
UPDATE
_layout.cshtm file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - Test</title>
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
#RenderSection("styles", required:false)
</head>
<body>
<header>
<div class="container navbar navbar-inverse navbar-fixed-top text-center">
</div>
<div class="container nav nav-pills" style="margin-top:4px;background-color:cornsilk;">
#await Component.InvokeAsync("Welcome")
</div>
</header>
<div class="container body-content">
#RenderBody()
<hr />
<footer class="text-center">
<a asp-controller="Misc" asp-action="AccessibilityStatement" class="text-center text-muted">Accessibility Statement</a>
</footer>
</div>
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
#RenderSection("scripts", required: false)
#RenderSection("css", required:false)
</body>
</html>
I see. If you go and open Shared folder inside Views folder you will find a file called _ValidationScriptsPartial.cshtml that contains the validation scripts.
Now the first thing to do is to add validation attributes such as [Required] to your view model.
Than in Main View add #{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } before <script>.
After you add the html of the partial view in this line $('#menuAP').html(data);, find the form and call $.validator.unobtrusive.parse() like the following
if (BtnVal == 'AddOrderBtnGo') {
$('#menuAP').html(data);
var $form = $('#menuAP').find('#your-form-id-here');
$.validator.unobtrusive.parse($form);
}

Button click to display a table from mysql in ibm mobile first

I am in process of learning so kindly help me to do how the retrieval of table from mysql in ibm mobile first by just clicking an button from my html page. I have tried but not working help please
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>vikdemodb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div id="header">
<h1>database Demo</h1>
</div>
<div id="wrapper">
<input type="button" id="databasecon" value="click me to get data from db" /><br />
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
My main.js
function wlCommonInit(){
$('#databasecon').click(loadSQLRecords);
}
function loadSQLRecords(){
var invocationData = {
adapter : 'vikadap',
procedure : 'getstudinfo',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : loadSQLQuerySuccess,
onFailure : loadSQLQueryFailure
});
}
function loadSQLQuerySuccess(result){
window.alert("success");
console.log("Retrieve success" + result);
console.log(result.invocationResult.resultSet);
}
function loadSQLQueryFailure(result){
WL.Logger.error("Retrieve failure");
}
You have a button in your HTML:
<input type="button" id="databasecon" value="click me to get data from db" />
You handle this button in wlCommonInit():
$('#databasecon').click(loadSQLRecords);
In loadSQLRecords() you call an adapter procedure to retrieve data from the database. If this operation succeeds then it calls the loadSQLQuerySuccess callback function.
It is this function that you are supposed to handle the display of the response from the backend (your database). But what are you doing? You only print to the console the response. You do not handle at all, displaying it in the application - in the HTML.
So in your HTML, you need to prepare a place holder that you will append the result into. For example: <table id="mytable"></table>
Then you need to populate the table with the data...
So in loadSQLQuerySuccess, you could for example do the following... this is where you need to learn HTML and JavaScript to accomplish what YOU want it to look like:
function loadFeedsSuccess(result) {
if (result.invocationResult.resultSet.length > 0)
displayFeeds(result.invocationResult.resultSet);
else
loadFeedsFailure();
}
function loadFeedsFailure() {
alert ("failure");
}
function displayFeeds(result) {
for (var i = 0; i < result.length; i++) {
$("#mytable").append("<tr><td>" + result[i].firstName + "</td></tr>");
$("#mytable").append("<tr><td>" + result[i].lastName + "</td></tr>");
}
}
Note that you need to create your own code in the for loop to make it look like how you want it to look, and of course append your own properties from the database, instead of "firstName" and "lastName".

Opera extension error "Uncaught exception: ReferenceError: Security violation"

I am working on an opera extension. The extension have a popup that will open a website in it.
I get the below error at "xhr.send()" in popup.html file and i can't able to remove it.
"[4/14/2013 12:51:19 PM] JavaScript -
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html Inline
script thread Uncaught exception: ReferenceError: Security violation
Error thrown at line 30, column 16 in fetchGames() in
widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
xhr.send(); called from line 32, column 12 in widget://wuid-9ec76e79-06d9-2749-8b7e-b42743de3375/popup.html:
fetchGames(); "
My config file is as below:
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" id="http://www.example.org/helloworld">
<name>Hello Extensions!</name>
<description>A simple hello world example</description>
<author href="http://www.twitter.com/dstorey/" email="dstorey#opera.com">David Storey, Opera Software</author>
<icon src="icons/icon-64.png"/>
</widget>
My index.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Hello World!</title>
<meta charset="UTF-8">
<script>
window.addEventListener( 'load', function(){
var theButton;
var ToolbarUIItemProperties = {
disabled: false,
title: 'Hello World',
icon: 'icons/icon-18.png',
popup: {
href: 'popup.html',
width: 500,
height: 500
}
}
theButton = opera.contexts.toolbar.createItem(ToolbarUIItemProperties);
opera.contexts.toolbar.addItem(theButton);
}, false );
</script>
</head>
<body>
</body>
</html>
My popup.html file is:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
background-color: #efefef;
}
</style>
<script>
function fetchGames() {
alert('hello');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = (xhr.responseText);
document.getElementById('list_games').innerHTML = data;
//callback(data);
}
else {
alert('No Games Found');
window.close();
}
}
}
var url = 'http://www.anatomic.us/generate-xml';
xhr.open('GET', url, true);
xhr.send();
};
fetchGames();
function submitForm(obj)
{
var searchKey = document.getElementById('sp').value;
if(searchKey!=null && searchKey!='')
{
obj.setAttribute('action', 'http://www.3d-game.co/'+searchKey);
return true;
// chrome.tabs.create({url: 'http://www.3d-game.co/'+searchKey});
}
else
{
alert('Please Enter your search item');
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- <div class="header">
<img src="icon.png">
</div>
<br />-->
<div id=content>
<div style='padding-left:10px;'>
<form id=sf method=post action="http://www.3d-game.co/search/" onSubmit="return submitForm(this);" target="_blank">
</form>
</div>
<div id=cat_content>
<div id="list_games" class=list_games>
<img src="loader.gif" border="none" />
<div class="ajax-loader">
<img src="loader.gif" border="none" />
</div>
</div>
</div>
</body>
</html>
Plz help me in removing it.
Add following in the header of the file from where you are fetching the data:
Access-Control-Allow-Origin: *
in config.xml file add this line: to allow any domain httprequest before tab, this solve the problem, if problems persist, open in opera browser tab "opera:config" and select "Users Prefs" and check "Allow File XMLHttpRequest" and restart. if have problem i can send you my opera extension working fine...

How to run dojo from my own server (apache)..?

I have downloaded dojo build, now I have an doubt, in the below example code, I am using "dojo.js.uncompressed.js" as a start of source file, is it right? Just I want to display a button in the web page. Which one is the start file? in dojo library.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr">
<head>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="../dojo/lib/dojo/dojo.js.uncompressed.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dijit.form.Button");
dojo.addOnLoad(function() {
// Create a button programmatically:
var button = new dijit.form.Button({
label: "Click me!",
onClick: function() {
// Do something:
dojo.byId("result1").innerHTML += "Thank you! ";
}
},
"progButtonNode");
});
</script>
<link rel="stylesheet" type="text/css" href="../dojo/lib/dijit/themes/claro/claro.css" />
</head>
<body class=" claro ">
<button id="progButtonNode" type="button">
</button>
<div id="result1">
</div>
<!-- NOTE: the following script tag is not intended for usage in real
world!! it is part of the CodeGlass and you should just remove it when
you use the code -->
<script type="text/javascript">
dojo.addOnLoad(function() {
if (document.pub) {
document.pub();
}
});
</script>
</body>
</html>
dojo (and any js file) should be put next to your html files so that it is served by the server. Then you don't have to relate to long relative paths