I'm trying to send one of two different pieces of data to a database, depending on whether the user has checked an html checkbox. I can't figure out how to evaluate the checkbox using C#, without MVC. Here's what I've been trying in a simplified form:
@{
var Category = "";
var AltCategory = "";
var db = Database.Open("Inventory");
var Checkbox_value =(Request["altCategory_checkbox"]=="on") ? true : false;
if(IsPost && Validation.IsValid()){
Category = Request.Form["ListCategory"];
AltCategory = Request.Form["AltCategory"];
if(Checkbox_value = true){
Funcs.AddNewProduct(Category);
}
else{
Funcs.AddNewProduct(AltCategory);
}
Response.Redirect("~/Members/Products");}
}
And the html:
<form method="post">
<fieldset>
<p><label for="Category">Category:</label>
<input type="text" name="Category" value="@Request.Form["Category"]" />
</p>
<input type="checkbox" name="altCategory_checkbox" id="altCategory_checkbox">
<label for="altCategory_checkbox">Add new category?</label>
<p><label for="AltCategory">New category:</label>
<input type="text" name="New category" value="@Request.Form["AltCategory"]" />
</p>
<p><input type="submit" name="buttonSubmit" value="Add product" /></p>
</fieldset>
</form>
Any help is greatly appreciated, and I apologize if this is a trivial question.
The following ended up being a solution:
@{
var Category = "";
var AltCategory = "";
var db = Database.Open("Inventory");
if(IsPost){
Category = Request.Form["ListCategory"];
AltCategory = Request.Form["AltCategory"];
bool CategoryCheckbox = Request["CategoryCheckbox"].AsBool();
if(CategoryCheckbox){
Funcs.AddNewProduct(Category);
}
else{
Funcs.AddNewProduct(AltCategory);
}
Response.Redirect("~/Members/Products");}
}
With html:
<form method="post">
<fieldset>
<p><label for="Category">Category:</label>
<input type="text" name="Category" value="@Request.Form["Category"]" />
</p>
@Html.CheckBox("CategoryCheckbox", new { value = "true" })
<label for="CategoryCheckbox">Add new category?</label>
<p><label for="AltCategory">New category:</label>
<input type="text" name="New category" value="@Request.Form["AltCategory"]" />
</p>
<p><input type="submit" name="buttonSubmit" value="Add product" /></p>
</fieldset>
</form>
The trick is to read the checkbox as a bool
using bool CategoryCheckbox = Request["CategoryCheckbox"].AsBool();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.