简体   繁体   English

如何在ASP.NET MVC中正确获取复选框值?

[英]How to get checkbox value properly in ASP.NET MVC?

If formCollection[] is used, then the string returned for the checkbox as the result is: "true,false" . 如果使用formCollection[] ,则作为结果返回给checkboxstring为: "true,false" How do you parse this? 您如何解析呢? Is Replace() the only option? Replace()唯一的选择吗?

Or should i put all parameters in my "action method" (in controller)? 还是应该将所有参数都放在"action method" (在控制器中)? Like this: 像这样:

public ActionResult Edit(string checkbox)

What's the proper way? 正确的方法是什么?

UPDATE: for anyone who might run into this (thanks again @meda) 更新:对于任何可能遇到此问题的人(再次感谢@meda)

If you have a strongly typed view, something like this: 如果您具有强类型视图,则如下所示:

@model MyNamespace.Models.Car

then you can access the whole model in your controller like this: 那么您可以像这样在控制器中访问整个模型:

public ActionResult Edit(Car model)

or if you don't have that many "inputs" in your form, then you can use the names of your html inputs in your controller action method as parameters and the parameters will be parsed into the data type you want automatically: 或者,如果您的表单中没有那么多“输入”,则可以在控制器操作方法中使用html输入的名称作为参数,并且这些参数将自动解析为所需的数据类型:

public ActionResult Edit(bool checkbox)

The proper way is to not use formCollection and to pass a model object to your controller action. 正确的方法是不使用formCollection并将模型对象传递给控制器​​操作。

The model property would not be a string but a boolean since it could only be checked or unchecked. model属性不是字符串而是boolean因为只能选中或取消选中它。

For example: 例如:

public bool MyCheckBox1 { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM