Why does ASP.NET MVC Html.CheckBox output two INPUTs with the same name?

后端 未结 7 807
不知归路
不知归路 2020-12-03 17:07

Why in the world does the line:

<%= Html.CheckBox(\"ForSale\", Model.Product.ForSale)%> For Sale

result in the following HTML:

<
7条回答
  •  情歌与酒
    2020-12-03 17:28

    Now whenever I check the box and access Request.Form["ForSale"], I get the ridiculous answer of "true,false". Am I supposed to parse that?

    Try this:

    var ForSale = Convert.ToBoolean(Request.Form.GetValues("ForSale").First());
    

    UPDATED:

    What if in the next MVC build it will return the value in the revers order "false, true"? ... – Mastermind

    var ForSale = Request.Form.GetValues("ForSale")
        .Select(x => x.ToUpperInvariant()).Contains("TRUE");
    
    // or
    
    // FormatException can be thrown from Convert.ToBoolean()
    var ForSale = Request.Form.GetValues("ForSale")
        .Select(x => Convert.ToBoolean(x)).Contains(true);
    

提交回复
热议问题