Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to use Razor CheckBoxFor in MVC View

Razor CheckBoxFor helper creates checkboxes that don't seem to work correctly. The helper displays the current Model value just fine, but is always false on form submission - even when checked.

Lots of Google/SO results for this problem and many different workarounds. I found an HTML solution that allows the correct value on form submissions:

<input type="checkbox" id="IsActive" name="IsActive" 
       value="@(Model.IsActive ? "true" : "false")" 
       onchange="$(this).val(this.checked)"
       @(Model.IsActive ? "checked=checked" : "") />

The above works as-is, but I've been trying to understand how to accomplish the above using the CheckBoxFor helper, but all of my attempts take me right back to where it all started - submitted value is always false, even when checked.

@Html.CheckBoxFor(model => model.IsActive,
   new {
       @class = "form-check-input",
       name = "IsActive",
       onchange = "$(this).val(this.checked)",
       value = Model.IsActive ? "true" : "false"
   }
)

Why does the above HTML checkbox work, but CheckBoxFor is so impossible?

Btw, Model.IsActive is a bool, of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...