How to Save radio button value into SQLtable - sql-server

I want to add radio button values to my SQL table using ASP.NET MVC framework. I have a table with columns Approachability, Speed, Quality, and these three columns have to store the following values
Satisfied, Very Satisfied, Unsatisfied
so I am using the radio button for the values, but I don't know how to add the radio button value to the table please anyone help me.
Code that I have tried so far:
public class Customer
{
[Required]
public string Approachability { get; set; }
[Required]
public string Speed { get; set; }
[Required]
public string Quality { get; set; }
}
Controller:
[HttpGet]
public IActionResult AddCustomer()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddCustomer([Bind] Customer cust)
{
if (ModelState.IsValid)
{
objproject.AddCustomer(cust);
return RedirectToAction("Index");
}
return View(cust);
}
Database access:
public void AddCustomer(Customer cust)
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand("spAddCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Approachability", cust.Approachability);
cmd.Parameters.AddWithValue("#Speed", cust.Speed);
cmd.Parameters.AddWithValue("#Quality", cust.Quality);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Finally my view is:
<div class="col-md-10 offset-md-2">
<div class="row pt-2 row-space">
<div class="col-md-7">
<table class="table">
<thead>
<tr>
<th></th>
<th>Very Satisfied</th>
<th>Satisfied</th>
<th>Unsatisfied</th>
</tr>
</thead>
<tbody>
<tr>
<td>Approachability</td>
<td><input class="approachgroup" type="radio" asp-for="Approachability"name="approachgroup" value="Very Satisfied"></td>
<td><input class="approachgroup" type="radio" asp-for="Approachability" name="approachgroup" value="Satisfied"></td>
<td><input class="approachgroup" type="radio" asp-for="Approachability" name="approachgroup" value="UnSatisfied"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
For example, I am including only one field radio button

Okay, so regarding your specific case while there are solutions to use asp-for="SomeField", you can just match a view model field with the radio button's name field:
<tr>
<td>Approachability</td>
<td><input class="approachgroup" type="radio" name="Approachability" value="Very Satisfied"></td>
<td><input class="approachgroup" type="radio" name="Approachability" value="Satisfied"></td>
<td><input class="approachgroup" type="radio" name="Approachability" value="UnSatisfied"></td>
</tr>
When you submit your form, Approachability is populated with value of the checked radio button.

Related

Unable to display and update data from linked database into table in ASP.NET Core

I'm new to ASP.NET Core and I'm working on a student management web app using razor pages. I created a test database in Microsoft SQL Server containing a table called JITStudents which I'm trying to display on a table on the students "Registration" and "Manage Student" pages.
I created a Models folder in which I have a class JITStudents:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
using Microsoft.Data.SqlClient;
namespace JUI21.Models
{
public class JITStudents
{
[Key]
public int StudentID { get; set; }
[Required]
public string StdfirstName { get; set; }
[Required]
public string StdlastName { get; set; }
public int StdBirthDate { get; set; }
[Required]
public string Stdgender { get; set; }
public string StdPhone { get; set; }
[Required]
public string StdEmail { get; set; }
public string StdAddress { get; set; }
public string StdCity { get; set; }
public string StdState { get; set; }
public string StdZipCode { get; set; }
public string StdStatus { get; set; }
public List<JITStudents> GetJITStudentsParameters()
{
List<JITStudents> JITStudentsParameterList = new List<JITStudents>();
string connectionString = "Data Source=DESKTOP-IK1GLFJ\SQLEXPRESS;Initial Catalog=JITStuRegistry;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
string sqlQuery = "select JITStudentID, StdfirstName, StdlastName, StdBirthDate, Stdgender, StdPhone, StdEmail" +
"StdAddress, StdCity, StdState, StdZipCode, StdStatus";
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr !=null)
{
while (dr.Read())
{
JITStudents JITStudentsParameter = new JITStudents();
JITStudentsParameter.StudentID = Convert.ToInt32(dr["StudentID"]);
JITStudentsParameter.StdfirstName = dr["StdfirstName"].ToString();
JITStudentsParameter.StdlastName = dr["StdlastName"].ToString();
JITStudentsParameter.StdBirthDate = Convert.ToInt32(dr["StdBirthDate"]);
JITStudentsParameter.Stdgender = dr["Stdgender"].ToString();
JITStudentsParameter.StdPhone = dr["StdPhone"].ToString();
JITStudentsParameter.StdEmail = dr["StdEmail"].ToString();
JITStudentsParameter.StdAddress = dr["StdAddress"].ToString();
JITStudentsParameter.StdCity = dr["StdCity"].ToString();
JITStudentsParameter.StdState = dr["StdState"].ToString();
JITStudentsParameter.StdZipCode = dr["StdZipCode"].ToString();
JITStudentsParameter.StdStatus = dr["StdStatus"].ToString();
JITStudentsParameterList.Add(JITStudentsParameter);
}
}
return JITStudentsParameterList;
}
}
}
Then, to the ManageStudent.cshtml.cs file I added the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.RazorPages;
using JUI21.Models;
using System.Data.SqlClient;
using Microsoft.Data.SqlClient;
namespace JUI21.Pages.Student
{
public class ManageStudentModel : PageModel
{
public List<JITStudents> JITStudentsParameterList = new List<JITStudents>();
public void OnGet()
{
JITStudents jitstudents = new JITStudents();
JITStudentsParameterList = jitstudents.GetJITStudentsParameters();
}
}
}
Unfortunately for me, trying to use the foreach (var JITStudents in Model.JITStudentsParameterList) statement to display the data on my table in the ManageStudent.cshtml as seen in the code below:
#page
#model JUI21.Pages.Student.ManageStudentModel
#{
}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title brand-text font-weight-bold ">Manage Student</h3>
<div class="card-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="table_search" class="form-control float-right" placeholder="Search">
<div class="input-group-append">
<button type="submit" class="btn btn-default">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>StudentID</th>
<th>StdfirstName</th>
<th>StdlastName</th>
<th>StdbirthDate</th>
<th>StdGender</th>
<th>StdPhone</th>
<th>StdEmail</th>
<th>StdAddress</th>
<th>StdCity</th>
<th>StdState</th>
<th>StdzipCode</th>
<th>StdStatus</th>
</tr>
</thead>
<tbody>
#{
if (Model !=null)
{
foreach (var JITStudents in Model.JITStudentsParameterList)
{
<tr>
<td> #JITStudents.StudentID</td>
<td> #JITStudents.StdfirstName</td>
<td> #JITStudents.StdlastName</td>
<td> #JITStudents.StdBirthDate</td>
<td> #JITStudents.Stdgender</td>
<td> #JITStudents.StdPhone</td>
<td> #JITStudents.StdEmail</td>
<td> #JITStudents.StdAddress</td>
<td> #JITStudents.StdCity</td>
<td> #JITStudents.StdState</td>
<td> #JITStudents.StdZipCode</td>
<td> #JITStudents.StdStatus</td>
</tr>
}
}
}
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
Results in an error
'ManageStudentModel' does not contain a definition for 'JITStudentsParameterList' and no accessible extension method 'JITStudentsParameterList' accepting a first argument of type 'ManageStudentModel' could be found (are you missing a using directive or an assembly reference?)
For the registration page where I repeated the same data display process the error I get when clicking on the page from the nav menu is
One or more compilation references may be missing. If you're seeing this in a published application, set 'CopyRefAssembliesToPublishDirectory' to true in your project file to ensure files in the refs directory are published.
The type or namespace name 'RegistrationModel' does not exist in the namespace 'JUI21.Pages.Student' (are you missing an assembly reference?)
The type or namespace name 'RegistrationModel' does not exist in the namespace 'JUI21.Pages.Student' (are you missing an assembly reference?)
The type or namespace name 'RegistrationModel' does not exist in the namespace 'JUI21.Pages.Student' (are you missing an assembly reference?)
The type or namespace name 'RegistrationModel' does not exist in the namespace 'JUI21.Pages.Student' (are you missing an assembly reference?)
What did I do wrong how can I get it to work please help. For now, I'm just trying to display the records from the database on the table. If I can do so successfully, I'll like to move on to adding, updating, and deleting records on the database through the web app. The entire layout is complete and runs well when I manually enter records into the Html page like so;
#page
#model JUI21.Pages.Student.ManageStudentModel
#{
}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title brand-text font-weight-bold ">Manage Student</h3>
<div class="card-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="table_search" class="form-control float-right" placeholder="Search">
<div class="input-group-append">
<button type="submit" class="btn btn-default">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>StudentID</th>
<th>StdfirstName</th>
<th>StdlastName</th>
<th>StdbirthDate</th>
<th>StdGender</th>
<th>StdPhone</th>
<th>StdEmail</th>
<th>StdAddress</th>
<th>StdCity</th>
<th>StdState</th>
<th>StdzipCode</th>
<th>StdStatus</th>
</tr>
</thead>
<tbody>
<tr>
<td>183</td>
<td>John</td>
<td>Doe</td>
<td>04-24-1984</td>
<td>Male</td>
<td>505-875-1952</td>
<td>jdoe#gmail.com</td>
<td>15 Private Dr</td>
<td>Houston</td>
<td>TX</td>
<td>79105</td>
<td><span class="tag tag-success">Approved</span></td>
</tr>
<tr>
<td>219</td>
<td>Alexander</td>
<td>Pierce</td>
<td>9-14-1989</td>
<td>Male</td>
<td>702-875-1952</td>
<td>apierce#gmail.com</td>
<td>415 Gallileo St</td>
<td>Dallas</td>
<td>TX</td>
<td>79805</td>
<td><span class="tag tag-warning">Pending</span></td>
</tr>
<tr>
<td>657</td>
<td>Bob</td>
<td>Doe</td>
<td>04-24-1994</td>
<td>Male</td>
<td>813-891-7952</td>
<td>bdoe#gmail.com</td>
<td>1852 Mango Dr</td>
<td>Houston</td>
<td>TX</td>
<td>79105</td>
<td><span class="tag tag-primary">Approved</span></td>
</tr>
<tr>
<td>175</td>
<td>Caroline</td>
<td>Fru</td>
<td>12-07-1990</td>
<td>Female</td>
<td>818-952-0297</td>
<td>caro22#aol.com</td>
<td>5823 N Sunset Blvd</td>
<td>Los Angeles</td>
<td>CA</td>
<td>98716</td>
<td><span class="tag tag-danger">Denied</span></td>
</tr>
<tr>
<td>183</td>
<td>Jane</td>
<td>Doe</td>
<td>05-15-1988</td>
<td>Feale</td>
<td>575-435-0962</td>
<td>j8ne#gmail.com</td>
<td>115 4th St</td>
<td>San Antonio</td>
<td>TX</td>
<td>79415</td>
<td><span class="tag tag-success">Approved</span></td>
</tr>
<tr>
<td>219</td>
<td>Alex</td>
<td>Devoe</td>
<td>2-14-1984</td>
<td>Male</td>
<td>212-672-2846</td>
<td>adevoe#hotmail.com</td>
<td>8 Ball St</td>
<td>Silver Spring</td>
<td>MD</td>
<td>20104</td>
<td><span class="tag tag-warning">Pending</span></td>
</tr>
<tr>
<td>657</td>
<td>Olivia</td>
<td>Batupe</td>
<td>01-29-1978</td>
<td>Female</td>
<td>202-443-7869</td>
<td>olib1#gmail.com</td>
<td>4 Mimbo Dr</td>
<td>Laural</td>
<td>MD</td>
<td>20105</td>
<td><span class="tag tag-primary">Approved</span></td>
</tr>
<tr>
<td>175</td>
<td>Michael</td>
<td>Landis</td>
<td>08-07-1989</td>
<td>Male</td>
<td>505-322-8088</td>
<td>Mikel#aol.com</td>
<td>200 Mountain View Dr</td>
<td>Rio Rancho</td>
<td>NM</td>
<td>87144</td>
<td><span class="tag tag-danger">Denied</span></td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
Here is what it looks like when I run it;
UI image with manual entries
I'll like to get the app to look like this displaying records from the database instead.
Thanks for your help, anyone who can. I need guidance.

Index out of range blazor checkbox [duplicate]

This question already has an answer here:
Calling function from generated button in Blazor [duplicate]
(1 answer)
Closed 2 years ago.
I try to create the user management in blazor.
The check box is check/uncheck when I click on it. but when It showed index out of bound. I don't know what went wrong. just try with blazor wasb. please help check this. it is just a basic component but somehow I don't get used to its usage yet.
I try to create the user management in blazor.
The check box is check/uncheck when I click on it. but when It showed index out of bound. I don't know what went wrong. just try with blazor wasb. please help check this. it is just a basic component but somehow I don't get used to its usage yet.
#page "/manageuserrole/{userId}"
#inject HttpClient client
#inject IJSRuntime js
#inject NavigationManager uriHelper
<h3>User Roles</h3>
#if (manageUserRolesDto == null)
{
<text>Loading...</text>
}
#*else if (manageUserRolesDto.Length == 0)
{
<text>No Records Found.</text>
}*#
else
{
<EditForm Model="#manageUserRolesDto" OnValidSubmit="#UpdateUserRoles">
<table class="table table-striped">
<thead>
<tr>
<th>Role</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
{
<tr>
<td>#manageUserRolesDto.UserRoles[i].RoleName</td>
<td>
<div class="form-check m-1">
<input type="checkbox"
#bind="#manageUserRolesDto.UserRoles[i].Selected"
/>
</div>
</td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-success">
Submit
</button>
</EditForm>
}
#code {
[Parameter]
public string userId { get; set; }
ManageUserRolesDto manageUserRolesDto { get; set; }
protected override async Task OnInitializedAsync()
{
manageUserRolesDto = await client.GetFromJsonAsync<ManageUserRolesDto>("api/userroles/" + userId);
}
private void checkUserRole(int i)
{
manageUserRolesDto.UserRoles[i].Selected = !manageUserRolesDto.UserRoles[i].Selected;
}
async Task UpdateUserRoles()
{
await client.PutAsJsonAsync("api/userroles/" + userId, manageUserRolesDto);
uriHelper.NavigateTo("user");
}
async Task ManagePermission(string roleId)
{
}
}
#for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
{
int copy = i;
<tr>
<td>#manageUserRolesDto.UserRoles[i].RoleName</td> <-- this 'i' is OK
<td><div class="form-check m-1">
<input type="checkbox"
#bind="#manageUserRolesDto.UserRoles[copy].Selected" <-- i is not OK
/>
</div></td>
</tr>
}
The #bind is compiled to a lambda function that captures the variable.
Another option is to use a foreach() { } instead of a for() { }

Click flag to highlight issue

I have a table that lists various fields from a customer database. I'd like to add a new column with a grey flag (indicates no issues) If the user clicks the flag I'd like the flag to turn red (indicates there is an issue)
I'm using MVC, Angularjs and Font Awesome.
Could someone point me in the best direction please?
using System;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using Florence.Authentication;
using Florence.Data;
using Florence.Website.Models;
using Florence.Website.Models.Job;
namespace Florence.Website.Controllers
{
/// <summary>
/// </summary>
public class JobController : Controller
{
/// <summary>
/// Search jobs
/// </summary>
/// <returns>Job list</returns>
[AuthorizationFilter(PermissionList = "CanListJobs")]
public ActionResult Index()
{
return View("~/views/job/index.cshtml");
}
[AuthorizationFilter(PermissionList = "CanViewJobs", AllowLocalRequests = true)]
public ActionResult PdfView(int id)
{
using (var context = new FlorenceContext())
{
var job = context.Jobs
.Include(c => c.Customer)
.Include(c => c.Customer.Address)
.First(c => c.Id == id);
if (!HttpContext.Request.IsLocal && job.BelongsToCompanyId != DataBag.LoggedOnCompany.Id)
{
return new HttpUnauthorizedResult();
}
return View("~/views/job/pdf/view.cshtml", job);
}
}
It depends on your table structure, but you need to create either a new property in your array, for each row, or a new array with the same length as the original one. Then simply add a new column and detect any changes to that new property/array.
Here is a simple demo (click on text Icon to change the flag):
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.array = [
{"ID":12345,"Details":"ABC"},
{"ID":23456,"Details":"BCD"},
{"ID":34567,"Details":"CDE"},
{"ID":45678,"Details":"DEF"}
];
// a new array of the same length (a `map` of it)
$scope.flags = $scope.array.map(function(_){return false;});
$scope.submit = function(){
console.log($scope.flags); // (extra)
}
});
table, th, td {
border: 1px solid black;
}
.red {
color: red;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="submit()">
<table>
<tr>
<th ng-repeat="(key,value) in array[0]">
{{key}}
</th>
<th>
Flag
</th>
</tr>
<tr ng-repeat="data in array">
<td ng-repeat="(key,value) in data">
{{value}}
</td>
<td>
<span ng-click="flags[$index] = !flags[$index]">
<i ng-class="{'red':flags[$index]}">Icon</i>
</span>
</td>
</tr>
</table>
<!-- (extra) -->
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>

Getting dimension when try to get row count of web page table

I am try to get count of row of a web page table but I am getting dimension of the table.
I have file called TableRow class and this class using properties file "webelement.properties" .In properties file i have kept the path of web element
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TableRow {
protected static WebDriver driver;
#BeforeClass
public static void setup() {
driver = new FirefoxDriver();
driver.get("some url");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public Properties getWebElementDetails() throws IOException {
Properties p = new Properties();
// Read object repository file
InputStream stream = new FileInputStream(
new File(System.getProperty("user.dir") + "//src//com//properties//webelement.properties"));
p.load(stream);
return p;
}
public WebElement getElementByXPath(String Key) throws IOException {
Properties propertiesValue = getWebElementDetails();
try {
return driver.findElement(By.xpath(propertiesValue.getProperty(Key)));
} catch (Throwable t) {
// If element not found on page then It will return null.
return null;
}
}
#Test()
void testLogincase1() throws Exception{
Thread.sleep(2000);
System.out.println(getElementByXPath("tab")).getsize());
}
}
webelement.properties
tab=.//*[#id='LinkedForm_Organization_OfficeChild']/div[2]/div[1]/div/table/tbody/tr
HTML COde.
<div class="row">
<div class="column">
<table class="linked-record-table data-table">
<thead>
<tr>
<th>Details</th>
<th>Name</th>
<th>Address 1</th>
<th>Address 2</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
</tr>
</thead>
<tbody>
<tr class="data-row" data-is-new="false">
<input id="Organization_OfficeChild_R1_" type="hidden" value="1" name="Organization_OfficeChild_R1_"/>
<input id="Organization_OfficeChild_R1__pky" type="hidden" value="4223" name="Organization_OfficeChild_R1__pky"/>
<td>
<a class="link darker" href="/Office/Details/4223?mode=Edit&_fcl=Organization&_fky=2291">
</td>
<td>
<td>
<td>
<td>
<td>
<td>
</tr>
<tr class="data-row" data-is-new="false">
<tr class="data-row new-row-template" data-is-new="true">
<tr class="data-row new-row-template" data-is-new="true">
<tr class="data-row new-row-template" data-is-new="true">
</tbody>
</table>
</div>
What i am doing wrong . Please provide solutions.
Hi please identify the row and column of the table as below
List<WebElement> myrowcount = driver.findElements(By.xpath("//*[#class='linked-record-table data-table']/tbody/tr"));
System.out.println("Size of the row is : " + myrowcount.size());
List<WebElement> mycolumncount = driver.findElements(By.xpath("//*[#class='linked-record-table data-table']/tbody/tr/td"));
System.out.println("Size of the column is : " + mycolumncount.size());

Populating a drop down list with data from the database

I'm trying to populate a drop down list with data from the database, any help in the right direction would be appreciated
This is the form:
<div align="center">
<form:form action="saveLid" method="post" modelAttribute="lid">
<table border="0">
<tr>
<td>Street:</td>
<td>
<form:select path="streetcode">
<form:option value="-1" label="kies een street" />
<form:options items="${listStreet}" />
</form:select>
</td>
<td><form:errors path="streetcode" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
The controller:
#RequestMapping(value = "/saveLid")
private ModelAndView listStreet() {
List<Street> listStreet = lidDAO.listStreet();
ModelAndView model = new ModelAndView("saveLid");
model.addObject("listStreet", listStreet);
return model;
}
The DAOImpl:
#Override
public List listStreet() {
String sql = "SELECT streetcode, ressort_id, ressort, streetnumber, streetname FROM Street";
List listStreet = jdbcTemplate.query(sql, new RowMapper() {
#Override
public Street mapRow(ResultSet rs, int rowNum) throws SQLException {
Street str = new Street();
str.setStreetcode(rs.getInt("streetcode"));
str.setRessortId(rs.getInt("ressort_id"));
str.setRessort(rs.getString("ressort"));
str.setStreetname(rs.getString("streetname"));
return str;
}
});
return listStreet;
}
the model:
public class Street {
public int streetcode;
int ressortId;
String ressort;
public String streetname;
//getter and setters
}

Resources