Hello I am currently using Web Matrix to create a Hotel Booking website. I have had some prior expereince using Visual Studio 2010, but changed to Web Matrix as it seems to have quite a lot of information online. Following a tutorial on W3Schools to help me get the website started I have completed the tutorial but my registration page seems to have some sort of error.
This is following code:
#{Layout = "Layout.cshtml";
// Initialize page
var email = "";
var password = "";
var confirmPassword = "";
var ErrorMessage = "";
// If this is a POST request, validate and process data
if (IsPost)
{
email = Request.Form["email"];
password = Request.Form["password"];
confirmPassword = Request.Form["confirmPassword"];
if (email.IsEmpty() || password.IsEmpty())
{ErrorMessage = "You must specify both email and password.";}
if (password != confirmPassword)
{ErrorMessage = "Password and confirmation do not match.";}
// If all information is valid, create a new account
if (ErrorMessage=="")
{
var db = Database.Open("Users");
var user = db.QuerySingle("SELECT Email FROM UserProfile
WHERE LOWER(Email) = LOWER(#0)", email);
if (user == null)
{
db.Execute("INSERT INTO UserProfile (Email) VALUES (#0)", email);
WebSecurity.CreateAccount(email, password, false);
// Navigate back to the homepage and exit
Response.Redirect("Default.cshtml");
}
else
{ErrorMessage = "Email address is already in use.";}
}
}
if (ErrorMessage!="")
{
<p>#ErrorMessage</p>
<p>Please correct the errors and try again.</p>
}
}
<h1>Register</h1>
<form method="post" action="">
<fieldset>
<legend>Sign-up Form</legend>
<ol>
<li>
<label>Email:</label>
<input type="text" id="email" name="email" />
</li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password" />
</li>
<li>
<label>Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword" />
</li>
<li>
<p><input type="submit" value="Register" /></p>
</li>
</ol>
</fieldset>
</form>
This is the corresponding part of the tutorial, W3School ASP.NET Tutorial
Any other useful information or tutorials that I could follow to get this system well in to development feel free to share, deadline for testing phase isn't so far away.
Thanks!
Related
I have a Form that should pass data through POST request, but GET request is being used without passing the data and do model binding of asp core, so buz of that the method Registrationp is never reach if the attribute [HttpPost] is in place ;( .
I tried many ways to get over this problem but none if them worked, even though the other forms post the data and bind the model successfully
HTML:
#model Student_Training.Models.File;
<form method="post" asp-controller="Students" asp-action="Registrationp" enctype="multipart/form-data">
<label asp-for="FileRep" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" asp-for="FileRep" name="img" accept="image/*" class="form-control custom-file-input" />
<label class="custom-file-label"> Upload...</label>
</div>
</div>
<div class="form-group">
<button id="Button" type="submit" name="submit" formmethod="post" class="btn btn-secondary btn-sm">
<a asp-action="Registrationp"> Save </a>
</button>
</div>
</form>
Controller POST method:
[HttpPost]
public async Task<IActionResult> Registrationp([Bind("FileId, FileName, OwnerId, FileRep")] Student_Training.Models.File imgFileModel, IFormFile img, int? id)
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
var userEmail = user.Email;
Student Student = _context.Student.FirstOrDefaultAsync(x => x.Email == userEmail).Result;
// StudentId
id = Student.StudentId;
// Save img to wwwroot/img folder
string wwwRootPath = _hostEnvironment.WebRootPath;
Student_Training.Models.File myFile = new Student_Training.Models.File();
string fileName = Path.GetFileNameWithoutExtension(imgFileModel.FileRep.FileName);
string extention = Path.GetExtension(imgFileModel.FileRep.FileName);
imgFileModel.FileName = fileName = fileName + DateTime.Now.ToString("yymmss") + extention;
string path = Path.Combine(wwwRootPath + "/img/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await imgFileModel.FileRep.CopyToAsync(fileStream);
}
// insert recorod to Db
_context.Add(imgFileModel);
await _context.SaveChangesAsync();
return View();
}
As a matter of fact you are using an ancor tag to submit your form, not a submit button. An ancor tag is always generates a GET request. So just remove it from your code:
<button id="submitButton" type="submit" class="btn btn-secondary btn-sm">Save</button>
I have an API that I've created for user registration / authentication, and similar operations. Example post method:
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]AuthenticateModel model)
{
var user = _userService.Authenticate(model.Username, model.Password);
if (user == null)
return BadRequest(new { message = "Username or password is incorrect" });
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role)
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
// return basic user info and authentication token
return Ok(new
{
user.Id,
user.Username,
Token = tokenString,
});
I now need my front-end to implement my API. So I'd like to call this API from a View. For example, say I want to create a simple login page:
<div class="row">
<div class="col-md-12">
<form method="post" action="">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
How would I now call the authenticate post method for this login form? As I have a controller which is the API controller, and I have a controller which is the action controller, for the users.
File structure if needed:
File structure
Calling your own web action can be done in mainly two ways:
Native HTML form submission.
AJAX
Native submit reloads your entire page. And address will be changed to the URL or your web action. Typically used as a search function, like:
<form asp-controller="Search" asp-action="Blogs" method="get">
<input type="text" name="question" />
<input type="submit" />
</form>
When the user submit the form with clicking the submit button, the browser will be redirect to /search/blogs?question=textHeInput.
To prevent page refreshing, you can submit a request with pure JavaScript. Which called AJAX.
https://en.wikipedia.org/wiki/Ajax_(programming)
For example:
// Require jQuery:
$.post('/authenticate', { "yourPropertyName" : "yourPropertyValue" }, function(response) {
// Do something after the request. Access response like this:
alert(response.Username);
});
And server responded username will shown.
You can use ASP.NET MVC Core Tag Helpers:
<form asp-controller="MyControllerName" asp-action="Authenticate" method="post">
<!-- Input and Submit elements -->
</form>
Since you're using JwtBearer with WebAPI's, an assumption is that you're probably going to call your authentication method using Ajax. Unfortunately you did not provide your class declaration showing your route convention for your ApiClass but normally it goes as "api/[Controller]"... If this is the case, you can do the following:
$("submitButton").click(
function authenticateUser()
{
$.post(
'/api/[COntrollerName]/authentication', // URL
$('#form").serialize(), // this is your form data as an object
function(payload) //Response
{
// do something with payload here
}
});
}
);
<button type="submit" class="btn btn-primary" id="submitButton">Login</button>
You might want to set your <button type="button"> so that the form doesn't submit. Attach a click event to that function, so that it processes the api call.
the name of God
and Hi to you
I created some login pages in asp.net
i want use SHA-1 algoritm for my passwords, it's mean, controller get password then send to SHA-1 function and then save it to db.
first: I have these cods in cshtml
<input type="text" name="Username" required="required" />
<label for="Username">Username</label>
<div>
<input type="password" name="Password" required="required"/>
<label for="Password">Password</label>
</div>
<div type="submit" class="button-container">
<button><span>Go</span></button>
</div>
after submit username and pass will be checked and if those be true an new page will be open and user login happen successfully but I don't have any idea about to show my login happened, let explain it whit a sample
I submit my login page and then this page will be open :http://localhost:19926/Home/Home because I used these codes(%1)
in html:
#using (Html.BeginForm("webAdminAccess", "Authentication")){
...myhtml codes...}
in controller:
public ActionResult webAdminAccess(string Username, string Password)
{
if (mLO.webAdminAccess(Username, Password))
{
return RedirectToAction("Home", "Home");
}
else
{
return View("webAdminAccessWrong");
}
}
and there is no difference if I run my project in visual and I put this link http://localhost:19926/Home/Home in my brower(%2)
now let me ask my question:
how make a difference between these two?(%1,%2)
what is Characteristic or Proprietary of a page that was open whit a login?
how make a difference between login as admin or login as client?
(I have admin class, authenticationController and use my sql)
tnx for you help
I have a question regarding emails, i want to send the whole contact form to email, and in this tutorial http://www.asp.net/web-pages/tutorials/email-and-search/11-adding-email-to-your-web-site it has almost everything except this line in code
// Send email
WebMail.Send(to: customerEmail,
subject: "Help request from - " + customerName,
body: customerRequest
);
}
i do not understand how to edit it,now the thing is it is working but only sending me customerRequest in email because now there is a form with more details and it is only sending customerRequest part not email , number, items and other categories, so kindly assist how to send the whole form or other columns through this.
Thanks
The customerRequest variable can contain any string you want it to contain. In the tutorial, it represents the value of the customerRequest form field. You can add other fields to the form and use their values to build up the body of the email. For example, you can add a partNumber field:
Your name:
<div>
Your email address:
<input type="text" name="customerEmail" />
</div>
<div>
Part Number:
<input type="text" name="partNumber" />
</div>
<div>
Details about your problem: <br />
<textarea name="customerRequest" cols="45" rows="4"></textarea>
</div>
<div>
<input type="submit" value="Submit" />
</div>
And in the server-side code, add that to the body:
#{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var customerRequest = Request["customerRequest"];
var partNumber = Request["partNumber"];
var errorMessage = "";
var debuggingFlag = false;
//etc
}
This is how you could concatenate the values:
WebMail.Send(to: customerEmail,
subject: "Help request from - " + customerName,
body: "Part Number: " + partNumber + "\n\n" + customerRequest
);
My notify url is not working even it is already activated in paypal. Is there something wrong with my code in the form? i have the same notify url in paypal account. By the way, I'm using heroku,spring mvc. Thanks. I hope you can help me.
<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_donations"/>
<input type="hidden" name="business" value="1234businessaccount#gmail.com"/>
<input type="hidden" name="item_name" value="${student.lastname }, ${student.firstname}"/>
<input type="hidden" name="currency_code" value="PHP"/>
<input type="hidden" name="lc" value="PH"/>
<input type="hidden" name="rm" value="2"/>
<input type="hidden" name="return" value="http://atriev.herokuapp.com/"/>
<input type="hidden" name="cancel_return" value="http://atriev.herokuapp.com/atriev-index.html"/>
<input type="hidden" name="notify_url" value="http://atriev.herokuapp.com/paypal.html"/>
paypal.jsp
<%# page import="java.util.*" %>
<%# page import="java.net.*" %>
<%# page import="java.io.*" %>
<%
// read post from PayPal system and add 'cmd'
Enumeration en = request.getParameterNames();
String str = "cmd=_notify-validate";
while(en.hasMoreElements()){
String paramName = (String)en.nextElement();
String paramValue = request.getParameter(paramName);
str = str + "&" + paramName + "=" + URLEncoder.encode(paramValue);
}
// post back to PayPal system to validate
// NOTE: change http: to https: in the following URL to verify using SSL (for increased security).
// using HTTPS requires either Java 1.4 or greater, or Java Secure Socket Extension (JSSE)
// and configured for older versions.
URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(str);
pw.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(uc.getInputStream()));
String res = in.readLine();
in.close();
// assign posted variables to local variables
String itemName = request.getParameter("item_name");
String itemNumber = request.getParameter("item_number");
String paymentStatus = request.getParameter("payment_status");
String paymentAmount = request.getParameter("mc_gross");
String paymentCurrency = request.getParameter("mc_currency");
String txnId = request.getParameter("txn_id");
String receiverEmail = request.getParameter("receiver_email");
String payerEmail = request.getParameter("payer_email");
if(res.equals("VERIFIED")) {
// check that paymentStatus=Completed
// check that txnId has not been previously processed
// check that receiverEmail is your Primary PayPal email
// check that paymentAmount/paymentCurrency are correct
// process payment
}
else if(res.equals("INVALID")) {
// log for investigation
}
else {
// error
}
%>