How do I connect my custom registration page to the model? - c#

I am new to Visual Studios MVC so please help me out. Every tutorial I have seen is using bootstrap to create registration pages. I created my own using HTML, Javascript, and CSS. Here is the template controller:
public ActionResult CreateAcct()
{
return View();
}
void ConnectionString()
{
con.ConnectionString = "Data Source=LAPTOP-3063L3HI\\SQLEXPRESS; database=betterpathdb;
Integrated Security=SSPI;";
}
public ActionResult Create(Staff reg)
{
string insertQuery = "INSERT INTO
staff(username,password,first,last,position) " +
"VALUES('" + reg.username + "', '" + reg.password + "', '" +
reg.first + "', '" + reg.last + "', '" + #position + "')";
con.Open();
com = new SqlCommand(insertQuery, con);
com.Parameters.AddWithValue("#position", position);
if (com.ExecuteNonQuery() == 1)
{
con.Close();
return View("");
}
else
{
con.Close();
return View("Error");
}
Here is the HTML template:
<div class="form">
<form action="Create" method="post">
<h1>BetterPath Wellness</h1>
<h4>Create Account or</h4>
<div>#Html.ActionLink("Login", "IndexLogin")</div>
<div class="txt-block">
<label for="us-fname">First:</label><br>
<input type="text" name="fname" id="fname">
<label for="us-lname">Last:</label><br>
<input type="text" name="lname" id="lname">
</div>
<div class="txt-block">
<label for="us-pos">Position:</label>
<input type="radio" name="position" value="therapy">Therapist
<input type="radio" name="position" value="observer">Observer
<input type="radio" name="position" value="admin">Admin
</div>
<div class="txt-block">
<label for="username">Username:</label><br>
<input type="text" name="username" id="username">
</div>
<div class="txt-block">
<label for="password">Password:</label><br>
<input type="password" name="password" id="password">
</div>
<div class="btn-container">
<button id="btn" type="submit">Create</button>
</div>
</form>
</div>
I think my connection string for "create" is not right?

Add [HttpPost] tag to your action. Default verb is Get.
[HttpPost]
public ActionResult Create(Staff reg){
...
}

Related

ASP Core model binding not working after adding some elements by AJAX

I added some html elements (drop-downs) by using AJAX. After that, when I want to bind their inputs to my DTO(CreateSmsPattern) via submitting my form, seems not be bind correctly.
JQuery code:
$.ajax({
url: '/api/SmsPattern/GetSmsPatternParameterPersianName',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: false,
processData: false,
type: 'GET',
success: function (resp) {
if (resp != null) {
var options = "";
var json = JSON.parse(resp);
options += '<option value="0">انتخاب متغیر...</option>';
for (var i in json) {
var subJson = json[i];
var name = subJson.Name;
var id = subJson.Id;
options += '<option value="' + id + '">' + name + '</option>'
}
var first = $('#smsPatternParametersList').firstElementChild;
while (first) {
first.remove();
first = e.firstElementChild;
}
for (var i = 0; i < count; i++) {
$('#smsPatternParametersList').append(
`<select class="form-control" asp-for="Command.Parameter` + i + `">` + options + `</select>
<span asp-validation-for="Command.Parameter` + i + `" class="error"></span>
`);
}
}
}
});
My form (count of drop-downs depends on number that user types in input element id=smsPatternParametersCount):
<form method="post">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label asp-for="Command.Name" class="control-label">عنوان</label>
<input type="text" class="form-control" asp-for="Command.Name">
<span asp-validation-for="Command.Name" class="error"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" asp-for="Command.SpecialListId">فهرست ویژه</label>
<select class="form-control" asp-for="Command.SpecialListId" asp-items='new SelectList(Model.SmsSpecialLists, "Id", "Name")'>
<option value="0">انتخاب فهرست ویژه...</option>
</select>
<span asp-validation-for="Command.SpecialListId" class="error"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label asp-for="Command.ParametersCount" class="control-label">تعداد متغیرها</label>
<input type="number" id="smsPatternParametersCount" class="form-control" asp-for="Command.ParametersCount" min="1">
<span asp-validation-for="Command.ParametersCount" class="error"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group no-margin">
<label asp-for="Command.Message" class="control-label">متن همراه با متغیرها</label>
<textarea class="form-control" asp-for="Command.Message"
style="overflow: hidden; word-wrap: break-word; resize:none" rows="5"></textarea>
<span asp-validation-for="Command.Message" class="error"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">فهرست متغیرها</label>
<div id="smsPatternParametersList">
</div>
</div>
</div>
</div>
<a asp-page="Index" class="btn btn-dark m-b-5">بازگشت</a>
<button permission="#(int)SmsPermissions.SmsPattern.Create" type="submit" class="btn btn-info">ایجاد</button>
</form>
and back-end screenshot (هیچکدام means 'none'):
screenshot
I solved this problem. Just changed below part of jquery code:
$('#smsPatternParametersList').append(
`<select class="form-control" asp-for="Command.Parameter` + i + `">` + options + `</select>
<span asp-validation-for="Command.Parameter` + i + `" class="error"></span>
`);
to
$('#SmsPatternParametersList').append(
`<select class="form-control" id="Command_Parameter` + i + `" name="Command.Parameter` + i + `">` + options + `</select>
<span data-valmsg-replace="true" data-valmsg-for="Command.Parameter` + i + `" class="error field-validation-valid"></span>
`);
Seems when Ajax is fullfilling html, ASP.NET tag helper (ex. 'asp-for' or 'asp-validation-for') is not working at all. Thus, I used native html attributes.

Dynamically add rows in ASP.NET MVC table form

I'm trying to program an "add" button below an ASP.NET MVC table to dynamically append a blank row, and then have a submit button to save each row to the database with one click.
There are several similar questions on SO but none that I have been able to apply to this. I've been trying to apply this example but the "add" button is not appending new rows.
Model:
public class TableForm
{
public int Id { get; set; }
public List<TableFormData> TableFormDatas { get; set; }
}
public class TableFormData
{
public int Id { get; set; }
public string ClientSampleID { get; set; }
public string AdditionalComments { get; set; }
public string AcidStables { get; set; }
Razor view:
#model NewTestSix.Models.TableForm
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Sample submission</legend>
<table id="submissionTable" class="table table-bordered">
<thead>
<tr>
<td>Sample ID</td>
<td>Additional Comments</td>
<td>Acid-stable amino acids</td>
</tr>
</thead>
<tr id="tablerow0">
<td>
<div class="editor-field">
<input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
</div>
</td>
<td>
<button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
</td>
<td>
</td>
</tr>
</table>
<p>
<button id="add" type="submit" class="btn btn-primary">Add</button>
</p>
<hr />
<p>
<input type="submit" value="Create" class="btn btn-default" />
</p>
</fieldset>
}
#section Scripts {
<script src="~/bundles/jqueryval.js" type="text/javascript">
var counter = 1;
$(function () {
$('#add').click(function () {
$('<tr id="tablerow' + counter + '"><td>' +
'<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
'</td>' +
'</tr>').appendTo('#submissionTable');
counter++;
return false;
});
});
function removeTr(index) {
if (counter > 1) {
$('#tablerow' + index).remove();
counter--;
}
return false;
}
</script>
I'm not too fussed about model binding with the controller at this stage, I just want to get this add button working. example controller:
[HttpPost]
public ActionResult Index(string any = "")
{
IList<TableForm> _TableForm = new List<TableForm>();
//Loop through the forms
for (int i = 0; i <= Request.Form.Count; i++)
{
var ClientSampleID = Request.Form["ClientSampleID[" + i + "]"];
var additionalComments = Request.Form["AdditionalComments[" + i + "]"];
var acidStables = Request.Form["AcidStables[" + i + "]"];
if (!String.IsNullOrEmpty(ClientSampleID))
{
_TableForm.Add(new TableForm { ClientSampleID = ClientSampleID, AcidStables = acidStables, AdditionalComments = additionalComments });
}
}
return View();
}
Thanks for any insights.
Current:
Desired after clicking "add" button:
Change your
<button id="add" type="submit" class="btn btn-primary">Add</button>
into
<button id="add" type="button" class="btn btn-primary">Add</button>
...as I don't think the "Add" button should ever make the browser do a form submission when clicked, it should only invoke your button's client-side 'click' event-handler.
Then remove src="~/bundles/jqueryval.js" part from your script element's opening tag: inline scripts cannot have a src="" attribute.
Like this:
<script type="text/javascript">
var counter = 1;
//... the rest of your code is here...
</script>
If you actually have a jqueryval.js file, put it in another <script> tag.
Here is the result you are expecting if I'm not mistaken.
var counter = 1;
$(function () {
$('#add').click(function () {
$('<tr id="tablerow' + counter + '"><td>' +
'<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
'</td>' +
'</tr>').appendTo('#submissionTable');
counter++;
return false;
});
});
function removeTr(index) {
if (counter > 1) {
$('#tablerow' + index).remove();
counter--;
}
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>Sample submission</legend>
<table id="submissionTable" class="table table-bordered">
<thead>
<tr>
<td>Sample ID</td>
<td>Additional Comments</td>
<td>Acid-stable amino acids</td>
</tr>
</thead>
<tr id="tablerow0">
<td>
<div class="editor-field">
<input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
</div>
</td>
<td>
<button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
</td>
<td></td>
</tr>
</table>
<p>
<button id="add" type="button" class="btn btn-primary">Add</button>
</p>
<hr />
<p>
<input type="submit" value="Create" class="btn btn-default" />
</p>
</fieldset>
Let me know if it helps.
You can used jQuery jqGrid
It is jquery plugin which is free and open source. This is completely
Ajax enabled to display tabular data and to manipulate. Additionally,
we can apply different Jquery UI theme, see the demo.
Action Method: There is nothing here since we will be getting product details using Ajax in json format.
public ActionResult GetProducts(string sidx, string sord, int page, int rows)
{
var products = Product.GetSampleProducts();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = products.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var data = products.OrderBy(x => x.Id)
.Skip(pageSize * (page - 1))
.Take(pageSize).ToList();
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = data
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
And add this tag to target page
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
After that in script section add this:
<script>
var myGrid = $('#jqGrid');
myGrid.jqGrid({
url: '/Home/GetProducts/',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'GET',
colNames: ['ProductID', 'Name', 'Price', 'Department', 'Action'],
colModel: [
{ name: 'Id', key: true, width: 75 },
{ name: 'Name', key: true, width: 200 },
{ name: 'Price', key: true, width: 75 },
{ name: 'Department', key: true, width: 200 },
{ name: 'Edit', key: true, width: 100, editable: true, formatter: editButton }
],
rowNum: 4,
pager: '#jqGridPager',
gridview: true,
rownumbers: true,
pagerpos: 'center'
});
</script>
Original post is here
var counter = 2;
$(function () {
$('#add').click(function () {
$('<tr id="tablerow' + counter + '"><td>' +
'<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
'</td>' +
'<td>' +
'<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
'</td>' +
'</tr>').appendTo('#submissionTable');
counter++;
return false;
});
});
function removeTr(index) {
if (counter > 1) {
$('#tablerow' + index).remove();
counter--;
}
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>Sample submission</legend>
<table id="submissionTable" class="table table-bordered">
<thead>
<tr>
<td>Sample ID</td>
<td>Additional Comments</td>
<td>Acid-stable amino acids</td>
</tr>
</thead>
<tr id="tablerow0">
<td>
<div class="editor-field">
<input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
</div>
</td>
<td>
<div class="editor-field">
<input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
</div>
</td>
<td>
<button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
</td>
<td></td>
</tr>
</table>
<p>
<button id="add" type="button" class="btn btn-primary">Add</button>
</p>
<hr />
<p>
<input type="submit" value="Create" class="btn btn-default" />
</p>
</fieldset>

Insert time and datetime in azure db using C# and AngularJS

right now I am working on a web-site and I need to insert some users into my database using C# for backend and AngularJS for frontend. If I use postman, everything works fine, the routes are good, but I have a problem when I try to insert them via angularJS. Here is my db structure
my HTML code
<div class="main" ng-controller="newcandidateController as vm">
<form>
<div class="myInputs">
<div class="form-group">
<input type="text" placeholder=" Full name" id="i1" ng-model="vm.name">
</div>
<div class="form-group">
<input type="text" placeholder=" Email" ng-model="vm.email">
</div>
<div class="form-group">
<input type="text" placeholder=" Phone" ng-model="vm.phone">
</div>
<p id="username">Username: </p>
<p id="password">Password: </p>
<div>
<p>Position</p>
<select class="form-control" ng-model="vm.position">
<option ng-repeat="obj in vm.Tests">{{obj.testType}}</option>
</select>
</div>
<div class="form-check">
<br />
<label>Admin: </label>
<input type="checkbox" name="admin" id="checkbox" ng-model="vm.isadmin">
</div>
<input class="btn btn-info" type="button" value="Generate credentials" id="g" ng-click="vm.generate()">
<input class="btn btn-info" type="button" value="Submit" ng-click="vm.postUser()">
</div>
</form>
and my JavaScript file
vm.postUser = function () {
if (vm.position == "SysAdmin") {
vm.test = 2;
} else if (vm.position == "Java soft engineer") {
vm.test = 3;
} else if (vm.position == "SQL Solutions Architect") {
vm.test = 4;
} else {
vm.test = 5;
}
vm.date = "";
vm.time = "";
dataContext.addUser(vm.name, vm.email, vm.phone, vm.position, vm.username, vm.password, vm.isadmin, vm.test, vm.date, vm.time).then(
function (response) {
console.log(vm.name + " " + vm.email + " " + vm.phone + " " + vm.position + " " + vm.username + " " + vm.password + " " + vm.isadmin + " " + vm.test + " " + vm.date + " " + vm.time);
alert("It worked!");
},
function (error) {
console.log(error);
}
);
};
I don't know how to define a default value for date and time cuz at first I want them to be 0 and update it later.
Any help would be awesome, thank you!
edit:
Here is method where I post a user
public User CreateUser(User user)
{
db.User.Add(user);
db.SaveChanges();
return user;
}

How to connect server side programming (c#) on html button click [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 6 years ago.
Improve this question
I am rookie in this.
What I am trying to do is creating a simple login and register page using Html.Then I created a database in Mysql and I am using c# as my server side programming to interact with the database.(I don't wanna use PHP)
Now I need your help on how to connect my Html page to the c# program.
Here is my html code.
<div class="top-row">
<div class="field-wrap">
<label>
First Name<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Last Name<span class="req">*</span>
</label>
<input type="text"required autocomplete="off"/>
</div>
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email"required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Set A Password<span class="req">*</span>
</label>
<input type="password"required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Category(Doctor/Patient)<span class="req">*</span>
</label>
<input type="text"required autocomplete="off"/>
</div>
<button type="submit" class="button button-block"/>Get Started</button>
</form>
Here is my c# code
namespace dbsample
{
public partial class Form1 : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Form1()
{
InitializeComponent();
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "registerdatabase";
uid = "root";
password = "mysql";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
if (HttpContext.Current!=null)
{
var first_name =HttpContext.Current.Request.Form["first_name"];
var last_name = HttpContext.Current.Request.Form["last_name"];
var email_address = HttpContext.Current.Request.Form ["email_address"];
var category = HttpContext.Current.Request.Form["category"];;
string query = "INSERT INTO users_db (first_name,last_name,email_address,category) VALUES("+first_name+","+last_name+","+email_address+","+category+")";
}
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
private void Form1_Load(object sender, EventArgs e)
{
Insert();
}
}
}
So, how can I connect my HTML page to c#.
Thanks in advance
Maybe you want to convert your html code to asp.net web forms.
<body>
<form id="form1" runat="server">
<div>
<div class="top-row">
<div class="field-wrap">
<label>
First Name<span class="req">*</span>
</label>
<input type="text" autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Last Name<span class="req">*</span>
</label>
<input type="text" autocomplete="off" />
</div>
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Set A Password<span class="req">*</span>
</label>
<input type="password" autocomplete="off" />
</div>
<div class="field-wrap">
<label>
Category(Doctor/Patient)<span class="req">*</span>
</label>
<input type="text" autocomplete="off" />
</div>
<asp:Button ID="Button1" runat="server" Text="Get Started" CssClass="button button-block" />
</div>
</form>

Stop form post on page load

I have a search function which works. It searches for registered users, it works when you search only for their partial username, however, the problem with this is that when you load the page, it basically searches, but the search-string is empty, which means it returns every user. I need to make it so it only searches when you actually search. But I can't seem to figure out how to accomplish this. I guess basically I need to stop the form from posting on page load.
#{
Layout = "~/Admin/_SiteLayout.cshtml";
var db = Database.Open("MikZeRCoding2");
var userSearchQuery = "SELECT * FROM [Users] WHERE UserName LIKE '%' + #0 + '%'";
var UsernameSearch = "";
var ErrorMessage = "";
Validation.RequireField("search-username", "lel");
if (IsPost && Validation.IsValid()) {
UsernameSearch = Request.Form["search-username"];
if (UsernameSearch.IsEmpty()) {
ErrorMessage = "You didn't search for anything.";
}
if (!UsernameSearch.IsEmpty() && db.QueryValue(userSearchQuery, UsernameSearch) == null) {
ErrorMessage = "No results for '" + UsernameSearch + "' were found...";
}
else {
}
}
}
<div class="search-users">
<h2>Search users</h2>
<form method="post" action="">
<div class="input-group">
<input type="text" name="search-username" placeholder="Search for a user" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="button"></button>
</span>
</div>
<input type="submit" value="Search" />
#foreach(var user in db.Query(userSearchQuery, UsernameSearch)) {
<span>[ #user.UserId ]</span> #user.UserName
}
#if(!ErrorMessage.IsEmpty()) {
<div class="alert alert-danger">#ErrorMessage</div>
#Html.ValidationSummary()
}
</form>
</div>
Thank you in advance.
You could wrap your view of the users in a IsPost-statement;
#if(IsPost){
foreach(var user in db.Query(userSearchQuery, UsernameSearch)) {
<span>[ #user.UserId ]</span> #user.UserName
}
}

Categories

Resources