I'm creating a form so members of a site can change the passwords for their accounts, and I'd like to display a message explaining mistakes the users made while filling the fields (such as password too short, needs at least a non-alphanumeric character, etc.). I'd like to display these messages in the same page, beside the field names. Here's my code:
#helper RenderForm()
{
<form method="post">
<p>Change your password below</p>
<div><label for="currentPassword">Current Password</label>
<input type="password" id="currentPassword" name="currentPassword"/></div>
<div><label for="newPassword">New Password:</label>
<input type="password" id="newPassword" name="newPassword"/></div>
<div><label for="confirmPassword">Confirm New Password</label>
<input type="password" id="confirmPassword" name="confirmPassword"/></div>
<div><input type="submit" id="submit" name="submit" value="submit"/></div>
</form>
}
#helper Message(string message)
{
<p>#message</p>
}
<style type="text/css">
p,label {color:black;}
</style>
#{
if(!IsPost) {
#RenderForm();
}
else {
var account = Membership.GetUser();
var currentPassword = HttpContext.Current.Request["currentPassword"];
if(Membership.ValidateUser(account.UserName, currentPassword)){
var newPassword = HttpContext.Current.Request["newPassword"];
var confirmPassword = HttpContext.Current.Request["currentPassword"];
if(check(newPassword, confirmPassword)){
account.ChangePassword(account.ResetPassword(), newPassword);
}
}
else {
#Message("The password provided didn't match with the database.");
}
}
}
#functions{
List<string> check(string newPassword, string confirmPassword)
{
//just a place holder
return false;
}
}
I've tried adding a List to be filled when an error was found, and when the form was reloaded the message would be displayed, but the RenderForm() function can't find any reference to the List. How can I display these messages?
You should use the built in validation that comes with the Web Pages framework. I have an article that explains how to use it: http://www.mikesdotnetting.com/Article/191/Validation-In-Razor-Web-Pages-2
Related
I am currently working a asp.net blazor project. In my displayed page, I have a set of form inputs under a collapsible. What I would like to do is set up some C# code to check when a user has completed all of the inputs, and take that information to make something happen in response.
OnValidSubmit and OnInvalidSubmit events on EditForm are what you need.
#if (LastSubmitResult != null)
{
<h2>
Last submit status: #LastSubmitResult
</h2>
}
<EditForm Model=#Person OnValidSubmit=#ValidFormSubmitted OnInvalidSubmit=#InvalidFormSubmitted>
<DataAnnotationsValidator/>
<InputText For=Person.FirstName/>
<input type="submit" class="btn btn-primary" value="Save" />
</EditForm>
#code {
Person Person = new Person();
string LastSubmitResult;
void ValidFormSubmitted(EditContext editContext)
{
LastSubmitResult = "OnValidSubmit was executed";
}
void InvalidFormSubmitted(EditContext editContext)
{
LastSubmitResult = "OnInvalidSubmit was executed";
}
}
I’ve written a code snippet creates HTML form via C#. But I want the form’s fields to be bound class’s field after the form is submitted. How can I do that and check the result(if the class’s fields are filled)? Moreover, I don’t know how to test the code via Postman or Fiddle. Could you exemplify? For example, when the form is filled via a browser, I don’t know how to see the result forwarded to sent.
HTML form,
<form action="sent” method="POST"<br>
<label for="firstName">First Name Label:</label>
<input type="text" title="testTitle" name="firstName" placeholder="First Name" ><br>
<label for="lastName">Last Name Label:</label>
<input type="text" name="lastName" placeholder="Last Name" ><br>
<input type="submit" name = "noname">
</form>
Nancy,
Get("/form", parameters =>
{
// codes to construct the above HTML code
return Response.AsText(form.ToString(), "text/html");
}
// Received form information (fields)
Post("/sent”, _ =>
{
testClass receivedData = this.Bind<testClass>();
return new
{
success = true,
message = $"Record recieved First Name = {receivedData.Name}",
message2 = $"Record recieved Last Name = {receivedData.SurName}"
};
});
testClass,
public class testClass
{
public string Name { get; set; }
public string SurName { get; set; }
}
Serving your form should be easy with this working example.
Get("/api/base", _ =>
{
return Response.AsFile("content/Base.html", "text/html");
});
Make sure to add content folder and make files inside copy to output directory when newer.
make sure you close tags properly.
Also your form could just call a mapped api on submit like this
<form action="/api/submit" method="POST">
<br>
<label for="firstName">First Name Label:</label>
<input type="text" title="testTitle" id="firstName" placeholder="First Name"><br>
<label for="lastName">Last Name Label:</label>
<input type="text" id="lastName" placeholder="Last Name" ><br>
<input type="submit" id = "noname">
</form>
https://stackoverflow.com/a/53192255
Post("/api/submit”, args =>
{
//this.Request.Body;
var r = (Response)"";
testClass receivedData = this.Bind<testClass>();
r = (Response)$"Record recieved First Name = {receivedData.Name}"
+ Environment.NewLine +
$"Record recieved Last Name = {receivedData.SurName}";
r.StatusCode = HttpStatusCode.OK;
return r;
});
I Could be wrong, but I think it is because you are using a discard for the input.
I am making a web service project using Bootstrap (HTML&CSS) , Microsoft Access and ASP.NET.
I found a code from W3SCHOOLS of bootstrap login form :
<body>
<form method="POST" action="Login.aspx">
<div class="container">
<h2>Login area</h2>
<form class="form-inline" role="form">
<div class="form-group">
<label for="email">UserName:</label>
<input type="text" class="form-control" id="username1" name="username" placeholder="Enter UserName"/>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password1" name="password" placeholder="Enter password"/>
</div>
<button type="submit" onclick="SubmitForm" class="btn btn-default">Submit</button>
</form>
</div>
And this is the C# code :
protected void SubmitForm(object sender, EventArgs e)
{
if (Page.IsValid)
{
string name=string.Format("{0}",Request.Form["username"]);
string pass = string.Format("{0}", Request.Form["password"]);
int userId;
userId = LoginService.GetUserId(name, pass, 0, 1);
if (userId == 0)
{
MessageBoxShow(Page, "UserName does not exists.");
}
else
{
MessageBoxShow(Page, "You are successfully connected.");
Session["userId"] = userId.ToString();
SalService.DeleteFromSal();
}
}
}
When I am running the page and entering username and password , the page doesnt show the message and I cant connect with the user name.
Put a breakpoint and check what is happening at the code-behind and what values are you receiving.
Also, Try using onserverclick instead of onclick.
<input id ="txt" runat="server" type="text">
and in behine
txt.value=#Your
Your HTML is not formatted using ASP serverside controls, however you can still get it to work. You have to change your button to a submit button.
<input type="submit" value="OK"/>
and then change your code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string name=string.Format("{0}",Request.Form["username"]);
string pass = string.Format("{0}", Request.Form["password"]);
int userId;
userId = LoginService.GetUserId(name, pass, 0, 1);
if (userId == 0)
{
MessageBoxShow(Page, "UserName does not exists.");
}
else
{
MessageBoxShow(Page, "You are successfully connected.");
Session["userId"] = userId.ToString();
SalService.DeleteFromSal();
}
}
}
Make sure that the code behind is for a page called login.aspx and should be called login.aspx.cs
There should be a login.aspx page and should have a valid page directive pointing to the code behind.
You will also need a function for MessageBoxShow and the Webservice should be referenced.
I have a update function like this:
public void Update(HomeBanner homebanner)
{
homebanner.EnsureValid();
DataSource.DataContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, homebanner);
DataSource.DataContext.SubmitChanges();
}
And i write a update controller
[AcceptVerbs(HttpVerbs.Post)]
//[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult ManageImages(int ? id,FormCollection form)
{
HomeBanner homebanner= BannerRepository.RetrieveById(id);
this.TryUpdateModel(homebanner);
string photoName = saveImage("photo");
if (photoName != string.Empty)
homebanner.ImageID = photoName;
BannerRepository.Update(homebanner);
return RedirectToAction("list", "Admin");
}
and then the view:
<% using (Html.BeginForm("ManageImages", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<h3>Manage Images</h3>
<div class="label-field">
<label for="ID">Chọn vị trí:</label>
<%= Html.DropDownList("ID", DataHelper.Banner().ToList().ToSelectList("value", "name",Model.HomeBanner.ID.ToString()))%>
</div>
<div class="label-field">
<label for="photo">
Chọn hình</label>
<input type="file" name="photo" value=""/>
</div>
<div class="label-field">
<label for="Link">
Liên kết</label>
<input type="text" name="Link"/>
</div>
<p>
<input type="submit" value="Lưu" />
</p>
<% } %>
It get data as well but update step is not success: It mark right here
DataSource.DataContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, homebanner);
and throw exception: An object specified for refresh is not recognized.
I dont know why, i see data filled to object when i debug. Plz someone help me!
Check the instance of DataContext there, maybe you are using different instance in which original object doesn't exists.
If it doesn't exist, you must first attach object to data context, then call refresh.
P.S. a tip: Make model or service for interacting with data, in controller it looks messy ;)'
I bump into this error because i was trying to update a just created object that did not exist yet on the database.
I have a C# aspx form in which I need to input it's data into an SQL database and then return a response saying successful or not. I have no idea how to get the form data that is sent from the Default.aspx page. My basic code structure is below:
Default.aspx
<form runat="server" name="aForm" action="Results.aspx" method="post" onsubmit="ValidateForm()">
<input name="firstname" type="text" />
<input name="surname" type="text" />
<input type="submit" value="Submit" />
</form>
Results.aspx.cs
public partial class AwardsForm : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack){
Response.Redirect("Default.aspx");
} else (this.IsPostBack) {
writeResults(FormSubmit());
}
protected boolean FormSubmit() {
// get form data and insert it into SQL
// return true/false based on success
}
protected void writeResults(boolean results) {
if (results == true) {
Response.Write ("Success");
} else {
Response.Write ("Failed");
}
}
}
You can get the posted form data through Request.Form["key"], or, if your form elements are decorated with runat="server" then you should be able to grab them by id right in your code behind
<asp:TextBox id="yourTb" runat="server"></asp:TextBox>
string postedText = yourTb.Text;
Or you can do (though this is much less common)
<input type="text" runat="server" id="yourOtherTb" />
string otherPostedText = yourOtherTb.Value;
Or if you're working with purely html form inputs:
<input type="text" id="clientTb" name="clientTb" />
string clientText = Request.Form["clientTb"];
You can try by the following code.
string firstname = Request.Form["firstname"]
string surname = Request.Form["surname"]
Since you are doing something like this
<input name="firstname" type="text" />
<input name="surname" type="text" />
<input type="submit" value="Submit" />
the name attribute of the input controls are posted back to the server(IIS). Hence you would do this.
If(IsPostBack)
{
string firstName = Request.Form["firstname"];
string surName = Request.Form["surname"];
if(string.IsNullOrEmpty(firstName))
{
Response.Write("Firstname is required this form");
}
}