Balanjaneyulu K
Balanjaneyulu K

Reputation: 4324

Set and Get the default value of checkbox in ASP.NET mvc

I am using Checkbox in my ASP.Net MVC project,

I can set check box by default as unchecked.

Age:
<input class="associationCheckbox" type="checkbox" name="age" />

When I post the form (For has only checkbox), the checkbox is not showing in formCollection (Here expected name and value are age, ‘false’).

Using below code,I was reading the velues.

 [HttpPost]
    public ActionResult Index(FormCollection formCollection)
    {
        foreach (var key in formCollection.Keys)
        {
            var value = formCollection[key.ToString()];
        }


        return RedirectToAction("CorticonIndex", "Test");
    }

If I check the check box at run time, then submit the form. I can get the name and value.

How to get the default values(false)If I don’t check checkbox?

I tried setting value property using model property but same issue is coming.

Model Class:

public bool CheckBoxvalue { get; set; }

this.CheckBoxvalue=false

Age: <input class="associationCheckbox" type="checkbox" name="age" [email protected] />

Can someone suggest me how to set and get default value.

I had look at below post from stack overflow but didn't info for my requirement.

How to set a CheckBox by default Checked in ASp.Net MVC

http://www.tutorialsteacher.com/mvc/htmlhelper-checkbox-checkboxfor

Thanks, Balu

Upvotes: 0

Views: 3867

Answers (1)

Jatin Nath Prusty
Jatin Nath Prusty

Reputation: 572

You can do something like this:

Age: <input class="associationCheckbox" type="checkbox" name="age" @(Model.CheckBoxvalue ? "checked" : "") [email protected] />

But it is always good to use HTMLHelper methods if you are using razor

Upvotes: 1

Related Questions