TinyMCE for WebPages Razor 2 - sql

I'm having some trouble using TinyMCE with ASP.NET Web Pages Razor 2. I'm trying to use TinyMCE with updating articles with SQL, however, it gives me this error:
"There was found a potentially dangerous Request.Form value for the client (Content="<p>Lorem ipsum dolor...")."
Linje 22: var update = "UPDATE [Tutorials] SET Heading=#0, Content=#1, Type=#2 WHERE ID=#3";
Linje 23: Heading = Request["Heading"];
Linje 24: Content = Request["Content"];
Linje 25: Type = Request["Type"];
Linje 26: db.Execute(update, Heading, Content, Type, TutorialId);
#{
Validation.RequireField("Heading", "Heading is required.");
Validation.RequireField("Content", "Content is required.");
Validation.RequireField("Type", "Type is required.");
var Heading = "";
var Content = "";
var Type = "";
var TutorialId = UrlData[0];
if (TutorialId.IsEmpty()) {
Response.Redirect("~/Members/Tutorials/List");
}
var db = Database.Open("MikZeRCoding2");
string htmlEncoded = WebUtility.HtmlEncode(Content);
if (IsPost && Validation.IsValid()) {
var update = "UPDATE [Tutorials] SET Heading=#0, Content=#1, Type=#2 WHERE ID=#3";
Heading = Request["Heading"];
Content = Request["Content"];
Type = Request["Type"];
db.Execute(update, Heading, Content, Type, TutorialId);
Response.Redirect("~/Members/Tutorials/List");
}
else {
var select = "SELECT * FROM [Tutorials] WHERE ID=#0";
var row = db.QuerySingle(select, TutorialId);
Heading = row.Heading;
Content = row.Content;
Type = row.Type;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Edit Tutorial - Admin Area</title>
</head>
<body>
<script type="text/javascript">
tinymce.init({selector:'textarea'});
</script>
<form method="post" action="">
<div class="content-container">
<ul>
<li>
<h3>Title</h3>
<input type="text" name="Heading" value="#Heading" />
</li>
<li>
<h3>Content</h3>
<textarea name="Content" id="content-editor">#Content</textarea>
</li>
<li>
<h3>Type</h3>
<input type="text" name="Type" value="#Type" />
</li>
<li>
<input type="submit" value="Update" />
#Html.ValidationSummary()
</li>
</ul>
</div>
</form>
</body>
</html>

You need to use Request.Unvalidated if you want to permit HTML to be posted:
Content = Request.Unvalidated("Content");
See more about request validation in ASP.NET Web Pages here: http://www.mikesdotnetting.com/Article/222/Request-Validation-In-ASP.NET-Web-Pages

Related

controller not sending to view .net core

controller not sending to view . I m trying to send request from controller to view , but its not redirecting . controller always redirect to index page. when i summit the form . its always redirecting same index page ,
controller not sending to view .controller not sending to view
My controller is sending to another view. but its not working .
public IActionResult userLogin([FromBody] Users user)
{
string apiUrl = "https://localhost:44331/api/ProcessAPI";
var input = new
{
email = user.email,
password = user.password
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
// client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/userLogin", inputJson);
// List<Users> customers = (new JavaScriptSerializer()).Deserialize<List<Users>>(json);
user = JsonConvert.DeserializeObject<Users>(json);
return View();
}
and the view page is
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#model myproject.Models.Users
#{
Layout = null;
}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Inventory Management System</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
#* <link rel="stylesheet" type="text/css" href="./includes/style.css">*#
#*<script type="text/javascript" rel="stylesheet" src="~/js/main.js"></script>*#
</head>
<body>
<div class="overlay"><div class="loader"></div></div>
<!-- Navbar -->
<br /><br />
<div class="container">
<div class="alert alert-success alert-dismissible fade show" role="alert">
#*<?php echo $_GET["msg"]; ?>*#
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#*<?php
}
?>*#
<div class="card mx-auto" style="width: 20rem;">
<img class="card-img-top mx-auto" style="width:60%;" src="./images/login.png" alt="Login Icon">
<div class="card-body">
<form id="form_login" >
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
#*<input asp-for="Name" type="text" class="form-control" id="name" required />*#
<input asp-for="email" type="email" class="form-control" id="log_email" placeholder="Enter email">
<small id="e_error" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="log_password" asp-for="password" id="log_password" placeholder="Password">
<small id="p_error" class="form-text text-muted"></small>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-lock"> </i>Login</button>
<span>Register</span>
</form>
</div>
<div class="card-footer">Forget Password ?</div>
</div>
</div>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#form_login").on("submit", function () {
var data = {
email: $("#log_email").val(),
password: $("#log_password").val(),
// Phone: $("#phone").val()
}
// data: $("#form_login").serialize(),
// var data = $("#form_login").serialize();
console.log(data);
$.ajax({
type: 'POST',
url: '/Process/userLogin',
// window.location.href = '#Url.Action("Process", "Dashboard")';
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
alert('Successfully received Data ');
console.log(result);
window.location.href = "Process/Dashboard";
// window.location.href = '#Url.Content("~/User/Home")';
// window.location.href = '#Url.Action("Process", "Dashboard")';
// window.location.href = DOMAIN + "/dashboard.php";
},
error: function () {
alert('Failed to receive the Data');
console.log('Failed ');
}
})
})
});
</script>
</body>
</html>
From your code, since you want to use JQuery Ajax to submit the form data to the action method, in the form submit event, you should use the event.preventDefault() to prevent the form submit action, then you can use JQuery Ajax to submit the form.
Second, does the Index page is the Process/Dashboard page? From your code, we can see in the Ajax success function, you will use the window.location.href to change the request URL, you can change the redirect page from here.

MVC Express - Data does not carry over in view once form is submitted

I am working on a very basic weather app to learn MVC architecture. However, I am having an issue with my page reloading once I submit the form and then data from that submission not coming over into the next newly rendered page.
Most of my logic for my page is in my controller.js file. In my view I have a form where the user fills in a city, and then my getWeather function makes an API call where it gets the city's temperature. From there my controller.js should re-render the index page, but pass in the string It is currently ${temp} °F in ${city}.
At least, that's how its supposed to work. Unfortunately when the page reloads the weather const is null and I then have my function catch the error and give me the message "that city is not available".
I have tested my API to make sure that it is correctly retrieving the data, by console.logging the res object, and I am getting that perfectly.
Also, I should note I bring in Weather function from my model. The only thing it does is test to see if the user inputted anything into the form and if they didn't it creates the error "Please enter the name of the city." I don't think it is the source of my issue or the fix for it.
I guess what I'm looking for is a way to prevent my page from reloading when I submit the form, or a way to not lose the data in my function when the page reloads. Any help would be greatly appreciated!
const axios = require('axios')
const API_KEY= "8d130a4fe5369b01d1fe629bccbe0926";
const Weather = require("../model/Weather")
exports.renderHomePAge = (req, res) => {
res.render("index")
}
exports.getWeather = (req, res, ) => {
const city = req.body.city
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=imperial`
const weather = new Weather(city)
weather.validateUserInput()
if(weather.errors.length){
res.render("index", {error: weather.errors.toString()})
} else {
axios.get(url)
.then((response)=>{
// console.log(response)
const {temp} = response.data.main
const {city} = response.data.city
res.render("index", {
weather: `It is currently ${temp} °F in ${city}.`
})
})
.catch((err) =>{
console.log(err)
res.render("index", {
weather: `That city is not avaible`
})
})
}
}
exports.renderAboutPAge = (req, res) => {
res.render("About")
}
I don't think its neccessary for this issue, but just incase here is my index.hbs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Weather | Home</title>
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about">About</a>
</li>
</ul>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-12 text-center main">
<div>
<h1 class="mt-5">MVC Weather Finder</h1>
<p class="lead">Enter the name of the city and press search!</p>
</div>
<div>
<form action="/" method="post">
<input name="city" type="text">
<button>Go!</button>
</form>
<div class="mt-3">
{{weather}}
{{error}}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
It turns out I was pulling data from my response object incorrectly and that was causing the issue.

Inserting into the db with PDO

<form action="uploads.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload</legend><br/>
Title: <input type="text" name="name" id="name" class="name" required> <br/><br/>
<textarea name="description" rows="6" cols="35" maxlength="120"></textarea><br/>
<input type="file" id="file" name="file[]" required multiple> <br/>
<input type="submit" id="submit" name="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will appear here.
</div>
<?php
// configuration
$dbhost = "localhost";
$dbname = "blog";
$dbuser = "root";
$dbpass = "pass";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$name = 'name';
$mime = 'mime';
$data = 'data';
$size = 'size';
$description = 'description';
$created = 'created';
$url = 'url';
// query
$sql = "INSERT INTO videos (name,mime,data,size,description,created,url) VALUES (:name,:mime,:data,:size,:description,:created,:url)";
$q = $conn->prepare($sql);
$q->execute(array(':name'=>$name,
':mime'=>$mime,
':data'=>$data,
':size'=>$size,
':description'=>$description,
':created'=>$created,
':url'=>$url));
?>
I'm not so good with PDO, I can get videos to upload to my db, but I can't take in a name or anything. It just shows: name, description, size is 0 and etc. I've watched a few tutorials, but none of them show how to add it by what the user names it or describes it as, only what they put into the values goes to the database. I've also searched around on here and many other websites, but no luck.

How to add autocomplete data into invoice dynamically

I am looking for a way to add autocomplete data from my code to an "invoice" page automatically. I want the user to be able to also click to add or remove each item(quickbooks style, with multiple form fields available, and adding dynamically) and in the long run, be able to drag elements to a certain position in the invoice. All I am looking for now is this :
good : pseudocode on how to do this
best : basic working code to take off with.
This is what I have so far :
Page that calls the data :
<?php
require 'database.php';
require 'results.php';
if(!empty($_GET['wid'])) { $wid = $_GET['wid']; }
elseif(!empty($_POST['wid'])) { $wid = $_POST['wid']; }
else { $wid = null; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/engine.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="span10 offset1">
<div class="row">
<h3>Add Item to Workorder</h3>
</div>
<form class="form-horizontal" action="additems.php" method="post">
<?php
// Add Custom Call for values from prior page ?>
<input type="hidden" name="wid" value="<?php echo htmlentities($wid); ?>">
<?php
//not required, but for get link purposes
if(isset($_POST['search']) && $_POST['search']!=''){
$search = $_POST['search'];
} elseif (isset($_GET['search']) && $_GET['search']!=''){
$search = $_GET['search'];
} else {
$search='';
}
//
echo"
<input type='text' class='search_input' name='search' id='search' placeholder='search' value='$search' autofocus>
<div id='search_output' class='search_output'>";
?>
Page that retrieves results :
<?php
require_once"database.php";//connection to database
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['search']) && $_POST['search']){
$search=$_POST['search'];
} elseif(isset($_GET['search']) && $_GET['search']){
$search=$_GET['search'];
}
if(isset($search)){
$search = '%' . strtr($search, ['%' => '\%', '_' => '\_']);
$search = str_replace(" ", "%", $search);
$search= "%$search%";
$sql="select * from products where `model` LIKE ? OR `category` LIKE ? OR `description` LIKE ? OR `subcategory` LIKE ? LIMIT 50;";
$statement = $pdo->prepare($sql);
$statement->execute([$search, $search, $search, $search]);
//configure for your custom data dump to autocomplete
echo "
<table class='table table-striped table-bordered' width='100%'>
<thead>
<tr>
<th>Model</th>
<th>Category</th>
<th>Description</th>
</tr>
</thead>
<tbody>
";
while($row = $statement->fetch()){
$item=$row['model'];
$title=$row['category'];
$description=$row['description'];
echo "
<tr>
<td>
<a href='?item=$item'>
$item
</td><td>
$title
</td><td>
$description
</a>
</td>
</tr>
";
}
//
}
This code contains Javascript and AJAX code which is for making dynamic search from the input and displaying the sql results in the 'search_output'.
<input type='text' class='search_input' onkeyup="performSearch(this.value);" id='search' placeholder='search' value='$search' autofocus>
<div id='search_output' class='search_output'>";
<script>
function performSearch(data) {
if (data.length > 0) {
var xmlhttp = new XMLHttpRequest() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("search_output").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "YOURPHPFILENAME.php?search=" + data, true);
xmlhttp.send();
}
}
</script>
Unfortunately for other Dynamic features you will need to learn JQUERY/AJAX and understand HTML DOM. There may be Third party API which may do this.

Dojo: How to show modal dialog on page load declaratively

I've created Modal Dialog box declaratively in dojo, and I want to show it to the user on page load, but I don't understand why the following code is not displaying anything on the browser on page load. Could anyone please tell me what wrong am I doing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Dijit!</title>
<!-- load Dojo -->
<link rel="stylesheet" href="../lib/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="../../css/style.css">
<script src="../lib/dojo/dojo.js" data-dojo-config="isDebug: true, async: true, parseOnLoad: true"></script>
<script>
require(["dojo/ready","dojo/parser","dijit/Dialog", "dijit/form/ComboBox", "dijit/Menu", "dijit/MenuItem", "dojox/form/PasswordValidator","dijit/form/ValidationTextBox","dijit/form/Form","dijit/form/SimpleTextarea","dijit/form/Button"]);</script>
</script>
</head>
<!-- set the claro class on our body element -->
<body class="claro">
<div data-dojo-id ="dialogOne" data-dojo-type = "dijit.Dialog" title = "Create Users" style="display: none">
<div class="dijitDialogPaneContentArea">
<div class = "formQuestion">
<span>Personal Details</span>
</div>
<div>
<label class = "firstLabel" for="Pname">Name </label>
<input type ="text" id ="Pname" data-dojo-type="dijit.form.ValidationTextBox"
data-dojo-props = "required :'true', invalidMessage:'',ucfirst:'true'" tabindex = '1'/>
<label class = "secondLabel" for = "combo">Role </label>
<Select id="combo" data-dojo-type="dijit.form.ComboBox" tabindex = '2'>
<option>Admin</option>
<option>User</option>
</Select><br>
<label class = "firstLabel" for="Pemail">Email</label>
<input type="text" id="Pemail" name="address"
data-dojo-type="dijit.form.ValidationTextBox"
data-dojo-props = "placeHolder:'(will be the username)',
trim:'true',
ucfirst : 'true'" tabindex = '3'/>
<label class = "secondLabel" for="Pmobile">Mobile</label>
<input type="text" id="Pmobile" name="address" tabindex = '4'
data-dojo-type="dijit.form.ValidationTextBox"
data-dojo-props = " trim : 'true',
regExp : '(\\d){10}',
invalidMessage : 'Mobile number is invalid',
ucfirst : 'true'" /><br>
<div dojoType="dojox.form.PasswordValidator"
name="password">
<div><label class = "firstLabel" for ="pass">Password </label><input type="password" id ="pass"
pwType="new" tabindex = '5'/>
<label class = "secondLabel" for ="confirm">Confirm Password </label><input type="password"
pwType="verify" tabindex = '6'/></div>
</div><br>
<div class ="dijitDialogPaneActionBar">
<button data-dojo-type = "dijit.form.Button" type ="submit" tabindex = '10' id = "ok" onClick="return dialogOne.isValid();">OK</button>
<button data-dojo-type = "dijit.form.Button" type = "button" tabindex = '11' onClick = "dialogOne.onCancel();" id = "cancel">Cancel</button>
</div>
</div>
<!-- This event is not firing -->
<script type="dojo/method" data-dojo-event="onLoad" >
dialogOne.show();
</script>
</div>
</body>
</html>​
Try the below code. Make changes to the loading dojo part to point to correct path of your dojo.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Dijit!</title>
<!-- load Dojo -->
<link rel="stylesheet" href="../dijit/themes/claro/claro.css">
<script src="../dojo/dojo.js" data-dojo-config="isDebug: true, async: true, parseOnLoad: true"></script>
<script>
require(["dojo/ready","dijit/Dialog", "dijit/form/ComboBox", "dijit/Menu", "dijit/MenuItem", "dojox/form/PasswordValidator","dijit/form/ValidationTextBox","dijit/form/Form","dijit/form/SimpleTextarea","dijit/form/Button","dojo/domReady!"]
, function(ready){
ready(function(){
console.debug("Ready!");
dialogOne.show();
});
});
</script>
</head>
<!-- set the claro class on our body element -->
<body class="claro">
<div data-dojo-id ="dialogOne" data-dojo-type = "dijit.Dialog" title = "Create Users" style="display: none">
<div class="dijitDialogPaneContentArea">
<div class = "formQuestion">
<span>Personal Details</span>
</div>
<div>
<label class = "firstLabel" for="Pname">Name </label>
<input type ="text" id ="Pname" data-dojo-type="dijit.form.ValidationTextBox"
data-dojo-props = "required :'true', invalidMessage:'',ucfirst:'true'" tabindex = '1'/>
<label class = "secondLabel" for = "combo">Role </label>
<Select id="combo" data-dojo-type="dijit.form.ComboBox" tabindex = '2'>
<option>Admin</option>
<option>User</option>
</Select><br>
<label class = "firstLabel" for="Pemail">Email</label>
<input type="text" id="Pemail" name="address"
data-dojo-type="dijit.form.ValidationTextBox"
data-dojo-props = "placeHolder:'(will be the username)',
trim:'true',
ucfirst : 'true'" tabindex = '3'/>
<label class = "secondLabel" for="Pmobile">Mobile</label>
<input type="text" id="Pmobile" name="address" tabindex = '4'
data-dojo-type="dijit.form.ValidationTextBox"
data-dojo-props = " trim : 'true',
pattern : '(\\d){10}',
invalidMessage : 'Mobile number is invalid',
ucfirst : 'true'" /><br>
<div dojoType="dojox.form.PasswordValidator"
name="password">
<div><label class = "firstLabel" for ="pass">Password </label><input type="password" id ="pass"
pwType="new" tabindex = '5'/>
<label class = "secondLabel" for ="confirm">Confirm Password </label><input type="password"
pwType="verify" tabindex = '6'/>
</div>
</div><br>
<div class ="dijitDialogPaneActionBar">
<button data-dojo-type = "dijit.form.Button" type ="submit" tabindex = '10' id = "ok" onClick="return dialogOne.isValid();">OK</button>
<button data-dojo-type = "dijit.form.Button" type = "button" tabindex = '11' onClick = "dialogOne.onCancel();" id = "cancel">Cancel</button>
</div>
</div>
</div>
</div>
</body>
</html>​
Try call the dialogOne.show() in the callback of the require function, change the "dojo/ready" into "dojo/domReady!" and place it at the end of the module array