简体   繁体   中英

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" . How do you parse this? Is Replace() the only option?

Or should i put all parameters in my "action method" (in controller)? Like this:

public ActionResult Edit(string checkbox)

What's the proper way?

UPDATE: for anyone who might run into this (thanks again @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:

public ActionResult Edit(bool checkbox)

The proper way is to not use formCollection and to pass a model object to your controller action.

The model property would not be a string but a boolean since it could only be checked or unchecked.

For example:

public bool MyCheckBox1 { get; set; }

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.

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