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

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;
}

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.

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

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){
...
}

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>

Problems routing with JSON

I'm working with JSON. But apparently I'm doing something wrong with my calls, because I'm not getting into the GetJSON_Register inside the AccountController. I'm no expert in Javascript at all, but I think it's a routing problem in my script.
As I said I'm not very good with Javascript so I'm just going to post all of my functions:
Register.cshtml
<form action="" method="post" role="form">
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" type="email" id="register-email" placeholder="Enter email" value="" required="required" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" type="password" id="register-password" placeholder="Enter password" value="" required="required" />
</div>
<div class="form-group">
<label for="repeatPassword">Repeat Password</label>
<input class="form-control" type="password" id="register-repeatPassword" placeholder="Repeat password" value="" required="required" />
</div>
<hr />
<div class="form-group">
<label for="firstname">Firstname</label>
<input class="form-control" type="text" id="register-firstname" placeholder="Enter firstname" value="" required="required" />
</div>
<div class="form-group">
<label for="lastname">Lastname</label>
<input class="form-control" type="text" id="register-lastname" placeholder="Enter lastname" value="" required="required" />
</div>
<button type="submit" class="btn btn-success" id="register-btn">Register</button>
<div id="message-register">
<span></span>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#register-btn').click(function () {
registera();
});
});
function registera() {
var $email = $('#register-email'),
$password = $('#register-password'),
$firstname = $('#register-firstname'),
$lastname = $('#register-lastname'),
$message = $('#message-register.span');
$message.className = 'alert';
showLoadingText($message);
register($email, $password, $firstname, $lastname, function(data) {
if (data.IsValid) {
$message.html('');
$message.className = '';
} else {
$message.className = 'alert alert-danger';
$message.html(data.Message);
}
});
};
</script>
script.js
function register(email, password, firstname, lastname) {
$.getJSON("/Account/GetJson_Register", { email: email, password: password, firstname: firstname, lastname: lastname }, function (data) {
return data;
});
};
AccountController.cs
public ActionResult GetJSON_Register(string email, string password, string firstname, string lastname)
{
string message = "";
bool success = true;
repository.Register(email, password, firstname, lastname);
if(Error.Instance.Message != "")
{
message = Error.Instance.Message;
success = false;
}
return Json(new { IsValid = success, Message = message }, JsonRequestBehavior.AllowGet);
}
EDIT
Tried changing the
<button type="submit" class="btn btn-success" id="register-btn">Register</button>
into
<input type="button" class="btn btn-success" id="register-btn" onclick="registera()" value="Register" />
and removed the .click event.
Now in my Chrome Javascript Console I get this message when clicking the button
Uncaught InvalidStateError: Failed to read the 'selectionDirection' property from 'HTMLInputElement': The input element's type ('email') does not support selection. jquery-latest.min.js:4
Vc jquery-latest.min.js:4
Vc jquery-latest.min.js:4
m.param jquery-latest.min.js:4
m.extend.ajax jquery-latest.min.js:4
m.(anonymous function) jquery-latest.min.js:4
m.extend.getJSON jquery-latest.min.js:4
register script.js:63
registera Register:213
onclick Register:180
GET http://localhost:1317/d61bfd81ee4f49eaae35adc38c5d9ea2/arterySignalR/ping?r…2Flocalhost%3A1317%2FAccount%2FRegister&browserName=Chrome&_=1411294396408 404 (Not Found) browserLink:37
send browserLink:37
p.extend.ajax browserLink:37
i.transports._logic.pingServer browserLink:62
(anonymous function) browserLink:62
I've found a solution. It seems like I'm passing an object from my Register.cshtml to the register function in script.js which takes in a value not an object.
So the solution is to change in Register.cshtml
register($email, $password, $firstname, $lastname, function(data) {
if (data.IsValid) {
$message.html('');
$message.className = '';
} else {
$message.className = 'alert alert-danger';
$message.html(data.Message);
}
});
into
register($email.val, $password.val, $firstname.val, $lastname.val, function(data) {
if (data.IsValid) {
$message.html('');
$message.className = '';
} else {
$message.className = 'alert alert-danger';
$message.html(data.Message);
}
});

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