Reading checkboxes using webmatrix/razor - sql

I'm having trouble with checkboxes on my site.
Here's the code I have so far:
#{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var db = Database.Open("StayInFlorida");
var rPropertyId = Request.QueryString["PropertyID"];
var Propertyinfo = "SELECT * FROM PropertyInfo WHERE PropertyID=#0";
var qPropertyinfo = db.QuerySingle(Propertyinfo, rPropertyId);
if(IsPost){
var sql = "INSERT INTO PropertyInfo (FePool, FeJac, FeGames) VALUES (#0, #1, #2) WHERE PropertyID=#3";
db.Execute(sql, Request["check1"], Request["check2"], Request["check3"], rPropertyId);
}
}
<form method="post">
<div>
<input type="checkbox" name="check1" value="true" />
Value 1
<br/>
<input type="checkbox" name="check2" value="check2" />
Value 2
<br/>
<input type="checkbox" name="check3" value="check3" />
Value 3
<br/>
<div>
<input type="submit" name="buttonSubmit" value="Submit" />
</div>
</form>
What I need to be able to do is check 3 columns in my database, and see if they are set to true (the columns are set as "bit"). If they are, then I want the checkbox to be shown as checked. I also want to be able to toggle these checkboxes and post "true" or "false" using a form, to post into the database.

You have a WHERE clause in your INSERT statement which makes no sense. If you are inserting, you create a new row. I suspect you intend to UPDATE an existing row in which case your SQL should be:
"UPDATE PropertyInfo SET FePool = #0, FeJac= #1, FeGames = #2 WHERE PropertyID=#3"
If a checkbox is not checked, nothing will be included for that checkbox in the Request.Form collection. If it is checked, the value passed is "on" by default, or whatever you have specified in the "value" attribute. For check1, that will be "true". For check2, that will be "check2". You need to establish whether the checkbox was actually included in the Request.Form collection and then set the values you want to commit to the database accordingly. If you want to pass true or false depending on whether the checkbox was checked, you can do this:
var c1 = !Request["check1"].IsEmpty();
var c2 = !Request["check2"].IsEmpty();
var c3 = !Request["check3"].IsEmpty();
var sql = "UPDATE PropertyInfo SET FePool = #0, FeJac= #1, FeGames = #2 WHERE PropertyID=#3";
db.Execute(sql, c1,c2,c3,rPropertyInfo);
Now that you have a series of booleans, you can use those to determine whether the checkbox is checked or not by using Conditional Attributes:
<input type="checkbox" name="check1" checked="#c1" /> Value 1<br/>
<input type="checkbox" name="check2" checked="#c2" /> Value 2<br/>
<input type="checkbox" name="check3" checked="#c3" /> Value 3<br/>
If you want to preset the values of the checkboxes from a query, you do that prior to the IsPost block:
var rPropertyId = Request.QueryString["PropertyID"];
var Propertyinfo = "SELECT * FROM PropertyInfo WHERE PropertyID=#0";
var qPropertyinfo = db.QuerySingle(Propertyinfo, rPropertyId);
bool c1 = qPropertyinfo.FePool;
bool c2 = qPropertyinfo.FeJac;
bool c3 = qPropertyinfo.FeGames;
Obviously you don't need var in front of the c1 - c3 variables in the IsPost block now.

Related

Select Option (for dropdown) Laravel

I make a dropdown for a form, I will show the code below. However, when I click the submit button, there is an error saying,
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'brand' cannot be null (SQL: insert into supplier_details.
The data that I chose from the dropdown is actually null. Actually, I'm new to Laravel.
I don't want to make a dropdown list from a database, I just want to display the option and the option will be inserted into the database when the user clicks the submit button after filling in the form.
<div class="form-group row">
<label style="font-size: 16px;" for="id" class = "col-sm-2">Item Brand </label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<select name="brand" class="form-control js-example-basic-single" required>
<option >Please select item brand</option>
<option value="machine1"> Item Brand 1 </option>
<option value="machine1"> Item Brand 2 </option>
<option value="machine1"> Tem Brand 3 </option>
</select>
</div>
</div>
Controller
public function createsupplierdetails()
{
return view ('frontend.praiBarcode.getweight');
}
public function supplierdetails(Request $r)
{
$details = new SupplierDetail;
$getuserPO = Supplier::where('PO',$r->PO)->first();
$details->brand = $getuserPO->brand;
$details->container_no = $getuserPO->container_no;
$details->date_received = $getuserPO->date_received;
$details->gross_weight = $getuserPO->gross_weight;
$details->tare_weight = $getuserPO->tare_weight;
$details->net_weight = $getuserPO->net_weight;
$details->save();
return view ('frontend.praiBarcode.viewsupplierdetails')
->with('details',$details);
}
This to check to verify if it is working:
Make sure you are submitting the correct form.
Try doing dd on your controller dd($request->all())
If data is reaching the controller and not inserted into the database, check on your model, if it is added to fillable or if there is only id in the guarded array. You can know about more here in https://laravel.com/docs/9.x/eloquent#mass-assignment
Error should be fixed, as soon as you fix it.
Controller
use Validator;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'brand' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->with('error', $validator->errors()->first());
}
$details = new SupplierDetail();
$details->brand = $request->brand;
$details->container_no = $request->container_no;
$details->date_received = $request->date_received;
$details->gross_weight = $request->gross_weight;
$details->tare_weight = $request->tare_weight;
$details->net_weight = $request->net_weight;
$details->save();
if ($trending) {
return redirect(route('details.index'))->with('success', 'Field added successfully');
} else {
return redirect()->back()->with('error', 'Field has been not added successfully');
}
}

Default value pre-selected in select box with ng-options

I am trying to get default value selected (from database) in my select box using ng-options.
My view
<select class="form-control samlength modalinput"
ng-options="p.procid as p.procname for p in processes track by p.procid"
ng-model="p.procid">
<option value="">-- choose an option --</option>
</select>
where p.procid is a value received from the database.
My data
procid procname time
1 MyProcess 2018-05-30 13:34:54.097 3003162
3 Testing 2018-05-31 18:31:32.467 3003162
If selected procid is 3, how can I get it to be selected by default?
FYI - I have tried multiple answers given in other threads. I have also tried ng-init but nothing helped.
You can keep your HTML as:
<select class="form-control samlength modalinput"
ng-options="p.procid as p.procname for p in processes track by p.procid"
ng-model="selectedProcess">
<option value="">-- choose an option --</option>
</select>
Now if we have a requirement to select a particular object in the array. We can do that by iterating through the array and comparing value at the given key:
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
Call this function as:
var index = functiontofindIndexByKeyValue($scope.processes, "procid", procid);
$scope.selectedProcess = $scope.processes[index];
alert(index);
Hope it works!
Update your html code to this:
<select ng-model="processSelected"
ng-options="p.procname for p in processes track by p.procid">
</select>
Then in controller initialise your model value as:
$scope.processSelected = $scope.processes[1];
Where $scope.processes is an array of process objects.
Plunker Example

How to assign null/string to an int type in MVC Razor using Entity Framework?

I am using a simple MVC 4 application using Entity Framework.
In my View I am displaying data from of a table using webgrid.
View Also has Textboxes(EditorFor) for saving any new record in the table.
I am using partial view for the Textboxes, as in the beginning when the page is launched, the textboxes should remain empty.
Out of 5, two columns are of integer types.
In order to make the textboxes empty initially I am using a new object as -
#if (!dataGrid.HasSelection)
{
Datamodel = new EntityFrDemo.Models.FacultyDetails { DepartmentID = 0, Name = "", Subject = "", YrsExp = 0, Email = "" };
Html.RenderPartial("~/Views/Shared/_FacultyDetails.cshtml", Datamodel);
}
//------------------------------------------------------------------------
#Html.LabelFor(model => model.DepartmentID)
#Html.EditorFor(model => model.DepartmentID)
#Html.ValidationMessageFor(model => model.DepartmentID)
//-----------------------------------------------------------------------------
So I am able to make my boxes empty, however for the Integer type boxes '0' is coming, as I can only assign zero.
So How can I override/superimpose the integer value type boxes to empty string type so that boxes remains empty only in case when no row is selected i.e. in initial stage...?
When you use #Html.EditorFor() with a int value, Razor generate a html tag like this
<input type="number" name="propertyName" id="propertyName" value="propertyValue" />
If you didn't set a value for the int property, the default int value is zero. To set another value in the html tag, you can write it without Razor or you can set the value like the code below.
#Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { #Value = "" } })
Note: It is capital "V", not a lower case "v".

ASP.NET Razor split record and increase by one

in my code I'm trying to display in a text box the record that follows the last one of my database. For example, if my last record is A560 I want to display A561. To achieve this I know I have to split the record and then manipulate it, but I haven't had any luck. Here is what the database looks like:
Point_ID Project No. Project Manager Comments
A558 1304 Oscar Duran Found destroyed
A559 1304 Oscar Duran Helicopter access
A560 1356 Julio Bravo Airport parking lot
This is my code so far:
#{
Layout = "~/_Layout.cshtml";
var db = Database.Open("ControlPoints");
var SelectCommand = "SELECT * FROM( SELECT TOP 5 * FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC )AS BaseData Order BY Point_ID ASC";
var SearchTerm = "";
if(!Request.QueryString["SearchCP"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE Point_ID = #0";
SearchTerm = Request.QueryString["SearchCP"];
}
if(!Request.QueryString["SearchProject"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE [Project Used on] LIKE #0";
SearchTerm = "%" + Request["SearchProject"] + "%";
}
var SelectData = db.Query(SelectCommand, SearchTerm);
var grid = new WebGrid(source: SelectData, rowsPerPage: 10);
}
#{
Validation.RequireField("Point_ID", " Required");
Validation.RequireField("ProjectNo", " Required");
Validation.RequireField("ProjectManager", " Required");
var Point_ID = "";
var ProjectNo = "";
var ProjectManager = "";
if(IsPost && Validation.IsValid() ){
Point_ID = Request.Form["Point_ID"];
ProjectNo = Request.Form["ProjectNo"];
ProjectManager = Request.Form["ProjectManager"];
db = Database.Open("ControlPoints");
var InsertCommand = "INSERT INTO AllControlMergedND ([Point_ID], [Project No.], [Project Manager]) VALUES(#0, #1, #2)";
db.Execute(InsertCommand, Point_ID, ProjectNo, ProjectManager);
}
var SelectLastCP = "SELECT TOP 1 Point_ID FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC";
var SelectData2 = db.QuerySingle(SelectLastCP);
var SuggestedPoint_ID = SelectData2.Point_ID;
}
<h2>Airborne Imaging Control Points Database</h2><br/><br/>
<form method="get">
<fieldset>
<legend>Search Criteria</legend>
<div>
<p><label for="SearchCP">Control Point ID:</label>
<input type="text" name="SearchCP" value="#Request.QueryString["SearchCP"]" />
<input type="submit" value="Search"/></p>
</div>
<div>
<p><label for="SearchProject">Project:</label>
<input type="text" name="SearchProject" value="#Request.QueryString["SearchProject"]" />
<input type="Submit" value="Search" /></p>
</div>
</fieldset>
</form>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Point_ID"),
grid.Column("Project No."),
grid.Column("Project Used on"),
grid.Column("WGS84 Lat"),
grid.Column("WGS84 Long"),
grid.Column("Ellips_Ht"),
grid.Column("Project Manager"),
grid.Column("Comments")
)
)
<br/><br/>
</div>
<form method="post">
<fieldset>
<legend>Create Control Point(s)</legend>
<p><label for="Point_ID">Point ID:</label>
<input type="text" name="Point_ID" value="#SuggestedPoint_ID" />
#Html.ValidationMessage("Point_ID")</p>
<p><label for="ProjectNo">Project No:</label>
<input type="text" name="ProjectNo" value="#Request.Form["ProjectNo"]" />
#Html.ValidationMessage("ProjectNo")</p>
<p><label for="ProjectManager">Project Manager:</label>
<input type="text" name="ProjectManager" value="#Request.Form["ProjectManager"]" />
#Html.ValidationMessage("ProjectManager")</p>
<p><input type="submit" name="ButtonConfirm" value="Confirm" /></p>
</fieldset>
</form>
As you can see, all I am able to do is to display the last record of my database in the text box, which in this case would be A560. The variable 'SuggestedPoint_ID' is holding that record. I have tried converting the data type, but had no success. Any help would be greatly appreciated.
Update:
What I need is to do the following. Split A560 in two parts 'A' and '560'. Then increment '560' by one to obtain '561' and finally attach 'A' again to '561' in order to obtain the next increment 'A561'.
If you are trying to convert "A560" to int for example then it won't work because you don't have a valid number. A needs to be removed.
var SuggestedPoint_ID = SelectData2.Point_ID.Replace("A", "");
This is not my recommended way to do it as A could be anything such as AA or B or ZZZZ. My point is that you need to describe what you need to get a better solution to your problem.
UPDATE
var source = "A560";
var lhs = source.Substring(0, 1);
var tmp = source.Replace(lhs, "");
int rhs;
if(int.TryParse(tmp, out rhs))
{
rhs++;
}
var result = string.Format("{0}{1}", lhs, rhs);

Yii Grid, multiple management rows

i have a questions about managament rows in grid. For example we have food/cost table like:
Fruit | cost
------------
Apple | 10$
Bannan| 5$
We can create form like:
<form>
<input type='text' name='Fruits[0][fruit] value='Apple' /> <input type='text' name='Fruits[0][cost] value='10$' /> <br>
<input type='text' name='Fruits[1][fruit] value='Bannan' /> <input type='text' name='Fruits[1][cost] value='5$' />
</form>
And save all it like:
if ($is_new)
if(isset($_POST['Fruits'])) {
foreach ($_POST['Fruits'] as $fruit) {
$model = new Fruit();
$model->attributes = $fruit;
$model->save();
}
}
} else { //here code for update, $model->load()... }
All fine, we can update both rows... But that if i want add new? All fine method above make all good, but what if i delete 1 row? In my base i will have 2 rows, but i need only 1.
Here 2 ways i see:
1. Delete all fruits from databse on every update when POST count != databse count
2. We can load database rows, write loop, check every row... but its so hard, so many code...
How you manage new and deleted rows?
Use Yii data handlers to print results, like 'CGridView' :
http://www.yiiframework.com/doc/api/1.1/CGridView/