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>
Related
This question already has an answer here:
Get ID and Value from a checkbox: Return to model and use in method to insert into sql database
(1 answer)
Closed 1 year ago.
I'm trying to add values to a cross table, where the ID of a garage and a value based on a list of choices gets inserted to the database. The list looks like following in the view:
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Claim</label>
<input type="checkbox" class="checkbclass" name="Claim" id="Claim" placeholder="Claim" required="" />
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Scheduled Service</label>
<input type="checkbox" class="checkbclass" name="Scheduled" id="Scheduled" placeholder="Scheduled" required="" />
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Tires</label>
<input type="checkbox" class="checkbclass" name="Tires" id="Tires" placeholder="Tires" required="" />
</div>
</div>
So 3 checkboxes is shown in the view. Here the user is supposed to choice one or more options when they edit a garage. The cross table looks like following:
[ID]
,[GarageID]
,[RequestProperty]
,[CreatedDate]
,[CreatedBy]
,[UpdatedDate]
,[UpdatedBy]
I would like to do something similar to this in SQL stored procedure:
INSERT INTO GarageCrossRequestType
(GarageID, RequestProperty)
VALUES (#GarageID, #RequestType)
Which could look something similar to:
var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd1.Parameters.AddWithValue("#RequestType", model.requestId);
int result = cmd1.ExecuteNonQuery();
if (result == 1)
valid = true;
In the method. (To insert the garageID and the RequestTypeID.)
The Request-types can be as following:
public int Claim { get; set; } = 1;
public int ScheduledService { get; set; } = 2;
public int Tires { get; set; } = 3;
So for example, if a user choose Claim, I would like to update the table with the GarageID and Claim -> which ID would be 1. I'm sort of new to working with views, so I'm not sure how I would connect the input types to the model. So the problems are as following:
Connect the input types to the model, giving them their correct value (ex. Claim -> 1, Scheduled -> 2 etcetera) and,
My database table only accept garageId and requestType, and therefore when sending for example garageId: 4, I would need the input type Claim or whatever checkbox is choosen to only send their value (1, 2 or 3) to the database.
Anyone got a solution for this? Also I hope this makes sense, let me know otherwise and i'll try to formulate it differently.
UPDATE:
So I should have explained better from the beginning. But here's the rest of the code. So basically, there's a function where a user can Edit a garage where I would like to make it possible for them to also choose either claim/service or tires. So I would like to expand this method, and when a user selects a garage this is when they also can choose claim etcetera (It's also from this method the garageId comes from).
In the view (for edit garage):
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Garage</label>
<input type="text" class="col-lg-10 form-control" name="GarageName" id="GarageName" placeholder="Name" required="" />
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Contact person</label>
<input type="text" class="col-lg-10 form-control" name="ContactPerson" id="ContactPerson" placeholder="ContactPerson" required="" />
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Email</label>
<input type="email" class="col-lg-10 form-control" name="Email" id="Email" placeholder="Email" required="" onblur="validateEmail(this.value);" /><p id="InvalidMeg" style="font-size: 25px; color: red">Invalid e-mail address</p>
</div>
</div>
<button class="btn btn-md btn-primary custom" type="submit" id="saveNewGarageBtn"><i class="glyphicon glyphicon-lock"></i> Save</button>
<button class="btn btn-md btn-primary custom" type="submit" id="EditGarageBtn"><i class="glyphicon glyphicon-lock"></i> Save edit</button>
Javascript:
function editGarage(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var garageId = dataItem.GarageId;
countryId = dataItem.CountryId;
name = dataItem.Name;
var contactperson = dataItem.ContactPerson;
var email = dataItem.Email;
if (garageId != 0) {
$("#EditGarageBtn").show();
$("#saveNewGarageBtn").hide();
$("#GarageName").val(name);
$("#Country").val(countryId);
$("#ContactPerson").val(contactperson);
$("#Email").val(email);
$("#garageId").val(garageId);
}
}
Edit-garage button:
$("#EditGarageBtn").click(function () {
var customerNumber = customerNumberOfEditingGarage;
name = $("#GarageName").val();
countryId = $("#Country").val();
var garageId = $("#garageId").val();
var contactperson = $("#ContactPerson").val();
var email = $("#Email").val();
$("#EditGarageBtn").hide();
if (countryId == "Norway")
countryId = 2;
if (countryId == "Finland")
countryId = 4;
if (name.length > 0 && email.length > 0 && phone.length > 0 && contactperson.length > 0) {
$.ajax({
url: '#Url.Action("EditGarage", "Garage")',
dataType: 'JSON',
data: {
name: name, countryId: countryId, garageId: garageId,
contactperson: contactperson,
phone: phone, email: email
},
success: function (data) {
if (data == "Failure") {
toastr["error"]("Error editing Garage");
}
else {
toastr["success"]("Garage successfully updated");
customerNumberOfEditingGarage = null;
refreshGrid();
}
},
error: function () {
}
});
} else {
toastr["error"]("Error editing Garage");
}
});
Method:
public bool EditGarage(GarageModel model)
{
var valid = false;
var cmd = new SqlCommand("spGarageEditGarage", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd.Parameters.AddWithValue("#CountryId", model.CountryId);
cmd.Parameters.AddWithValue("#ContactPerson", model.ContactPerson);
cmd.Parameters.AddWithValue("#Email", model.Email);
try
{
int result = cmd.ExecuteNonQuery();
if (result == 1)
valid = true;
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
Connection.Close();
}
return valid;
}
Hopefully, this became a bit clearer.
I do not know what your model is and where model.GarageId comes from. If you complete the part I did not understand, you can use the following code for model.requestId.
note: Use a radiobutton instead of a checkbox.
change view to :
#using (Html.BeginForm("YourAction", "YourController", FormMethod.Post))
{
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="radio" id="Claim" name="requestType" value="Claim">
<label for="Claim">Claim</label>
< </div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="radio" id="ScheduledService" name="requestType" value="ScheduledService">
<label for="ScheduledService">ScheduledService</label>
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="radio" id="Tires" name="requestType" value="Tires">
<label for="Tires">Tires</label>
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="submit" value="Submit"/>
</div>
</div>
</div>
}
add enum
public enum RequestType
{
Claim = 1,
ScheduledService = 2,
Tires = 3
}
in your action
public ActionResult YourAction(RequestType requestType)
{
//......................................
model.GarageId = //your value
switch (requestType)
{
case RequestType.Claim:
model.requestId = (int)RequestType.Claim;
break;
case RequestType.ScheduledService:
model.requestId = (int)RequestType.ScheduledService;
break;
case RequestType.Tires:
model.requestId = (int)RequestType.Tires;
break;
}
//get insert........................
}
Somebody good at MVC ASP.NET and C#?. Need a little help.
I'm creating a web application and i want to display a datagrid when clicking on CREATE BUTTON and it should allow me to select 1 or n tuples from that datagrid.
Take a look, i made this image:
How can i do that? I tried different thing but no one really worked :(
This is my code:
CONTEXT FILE:
public void CreateUser (User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("Create_user", con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#NAME", user.NAME);
cmd.Parameters.AddWithValue("#LAST", user.LAST);
cmd.Parameters.AddWithValue("#DESCRIPTION", user.DESCRIPTION);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Controller file (only the CREATE method is shown):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, [Bind] User user)
{
try
{
if (ModelState.IsValid)
{
dbContext.UpdateAprobador(user);
return RedirectToAction("Index");
}
return View(dbContext);
}
catch
{
return View();
}
}
My VIEW FILE:
#model WebApplicationNewsan.Models.User
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>User</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="NAME" class="control-label"></label>
<input asp-for="NAME" class="form-control" />
<span asp-validation-for="NAME" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LAST" class="control-label"></label>
<input asp-for="LAST" class="form-control" />
<span asp-validation-for="LAST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DESCRIPTION" class="control-label"></label>
<input asp-for="DESCRIPTION" class="form-control" />
<span asp-validation-for="DESCRIPTION" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I'm stuck on this situation and i dont understand how to make it works on MVC ASP.NET Core using C#
I created a viewgrid that allows me to Create, Update, Delete every single row shown in the grid. The problem is that everytime i click on CREATE it shows me a page where i can only write (manually) everything but instead of that i want my application to display another viewgrid (from a different database table) and allow the user to select the ROW or ROWS that he wants to add (something like a checkbox or whatever).
Take a look:
How can i do that?. I searched a lot but nothing really helped at all. Found something related to FORMS but not sure about that
This is my CONTEXT cs file:
public void CreateUser (User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("Create_user", con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#NAME", user.NAME);
cmd.Parameters.AddWithValue("#LAST", user.LAST);
cmd.Parameters.AddWithValue("#DESCRIPTION", user.DESCRIPTION);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
This is my Controller file:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, [Bind] User user)
{
try
{
if (ModelState.IsValid)
{
dbContext.UpdateAprobador(user);
return RedirectToAction("Index");
}
return View(dbContext);
}
catch
{
return View();
}
}
This is my VIEW file:
#model WebApplicationNewsan.Models.User
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>User</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="NAME" class="control-label"></label>
<input asp-for="NAME" class="form-control" />
<span asp-validation-for="NAME" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LAST" class="control-label"></label>
<input asp-for="LAST" class="form-control" />
<span asp-validation-for="LAST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DESCRIPTION" class="control-label"></label>
<input asp-for="DESCRIPTION" class="form-control" />
<span asp-validation-for="DESCRIPTION" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
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){
...
}
Im using bootstrap controls in my application.
I validating my page using jquery.validate.js and jquery.validate.unobtrusive.js.
I need to validate only visible controls, but im facing issues there.
Here is my code:
<div class="form-horizontal">
<div id="BaseQuesList_4" class="base-ques-list_4">
<h4 class="blue" style="font-weight: bold;">
Sample Questionnaire</h4>
<div class="hr hr-dotted">
</div>
<div class="space-12">
</div>
<div class="control-group info" ques-id="44" ctrl-type="radio">
<label class="control-label">
1
.
Physically isolated & access controlled ODC mandated?
</label>
<div class="controls">
<label class="inline">
<input type="radio" id="rdbBaseAns_38" name="44_question" ques-id="44" value="38" ans-id="38" ans-value="Yes" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> Yes</span>
</label>
<label class="inline">
<input type="radio" id="rdbBaseAns_39" name="44_question" ques-id="44" value="39" ans-id="39" ans-value="No" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> No</span>
</label>
</div>
</div>
<div class="Question_44">
<div base-ques-id="44" id="tblDeptQuesList_45" class="rscDeptQuest38" dept-class="DeptQuesList" style="display: block;">
<div class="control-group error" rsc-ques-id="45" rsc-ctrl-type="textbox">
<label class="control-label">
<i class="icon-hand-right blue"></i>
No. Visitor Policy Defined?
</label>
<div class="controls">
<input type="text" ques-id="45" number="true" data-val-required="Field is required" data-val="true" name="name_45" id="txtDeptAnswer_45">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
ConfigureValidator();
});
function ConfigureValidator() {
var basicDetailValidator = $('#Form1').data('validator');
var checkatleastOneCheckboxes = $("input[type='checkbox'][data-val-checkatleastone]");
checkatleastOneCheckboxes.each(function () {
var nameAttr = this.name;
basicDetailValidator.settings.rules[nameAttr].required = true;
basicDetailValidator.settings.messages[nameAttr].required = $(this).attr("data-val-checkatleastone");
});
basicDetailValidator.settings.errorElement = 'span';
basicDetailValidator.settings.errorClass = 'help-inline';
basicDetailValidator.settings.highlight = function (e) {
$(e).closest('.control-group').removeClass('info').addClass('error');
}
basicDetailValidator.settings.success = function (e) {
$(e).closest('.control-group').removeClass('error').addClass('info');
$(e).remove();
}
basicDetailValidator.settings.errorPlacement = function (error, element) {
if (element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('.controls');
if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
}
else if (element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
}
else {
error.insertAfter(element);
}
};
}
function GetQuesList(ddlAnswer) {
var QuestionId = $(ddlAnswer).attr('ques-id');
var AnswerId = $(ddlAnswer).val();
var className = "rscDeptQuest" + AnswerId;
$('div.Question_' + QuestionId + ' div[dept-class="DeptQuesList"]').css('display', 'none');
$('div.tab-content div[class="' + className + '"]').css('display', 'block');
}
</script>
I need to validate rdbBaseAns_39 control.If the option selectecd for rdbBaseAns_39 is Yes , then i need to validate txtDeptAnswer_45. but im validating all the controls all a stretch.
Please help me out.
Give the separate names name="44_question" like this name="44_question_1" for radio fields
<input type="radio" id="rdbBaseAns_38" name="44_question_1" ques-id="44" value="38" ans-id="38" ans-value="Yes" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> Yes</span>
<input type="radio" id="rdbBaseAns_39" name="44_question_2" ques-id="44" value="39" ans-id="39" ans-value="No" class="ace valid" data-val="true" data-val-required="Field is required" onclick="GetQuesList(this);"><span class="lbl"> No</span>