你如何使用C#评估一个html复选框?

时间:2016-05-06 07:36:57

标签: c# html mysql razor

我尝试将两个不同的数据中的一个发送到数据库,具体取决于用户是否已选中html复选框。我无法弄清楚如何使用C#,而不是 MVC来评估复选框。以下是我以简化形式尝试的内容:

@{
    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");}
}

和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> 

非常感谢任何帮助,如果这是一个微不足道的问题我会道歉。

1 个答案:

答案 0 :(得分:0)

以下结果是一个解决方案:

 @{
    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");}
} 

使用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> 

诀窍是使用bool

将复选框读作bool CategoryCheckbox = Request["CategoryCheckbox"].AsBool();