How to get checkbox value from FormCollection?

后端 未结 5 454
耶瑟儿~
耶瑟儿~ 2021-01-02 03:18

I have a checkbox and button:

@using(Html.BeginForm())
{
    
相关标签:
5条回答
  • 2021-01-02 03:28

    I have tried out with input tag and it works as shown below:

    <form method="post">
        <input type="checkbox" id="chkRmb" name="chkRmb" /> Remember Me?
        <input type="submit" value="Log In" class="btn btn-default login-btn" />
    </form>
    

    In the controller, compare the string value and convert its to a boolean.

    bool rmbMe = (formdata["chkRmb"] ?? "").Equals("on", StringComparison.CurrentCultureIgnoreCase);
    
    0 讨论(0)
  • 2021-01-02 03:33

    Try this, it solved this same issue for me. Thought I would share it in case others came upon this issue in the future.

    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        Boolean tempValue = collection["showAll"] != null ? true : false;
        TempData["showAll"] = tempValue;
    
        ... 
        something
        ...
    }
    
    0 讨论(0)
  • 2021-01-02 03:41

    I had trouble getting this to work and this is the solution I came up with. I'm showing it with an html helper.

    @Html.CheckBoxFor(model => model.showAll, new { @class = "form-control", Name = "showAll"})
    

    This is where I kept falling down and the following works.

    bool MyBoolValue= (collection["showAll"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);
    
    0 讨论(0)
  • 2021-01-02 03:42

    So I gave this a shot and it seemed happy to take it, where collection is my FormCollection object:

    if (collection.AllKeys.Contains("Inactive"))
    {
         np.Inactive = false;
    }
    else
    {
        np.Inactive = true;
    }
    

    Please be advised that the name of the targeted element is confusing - but this was the intended result I was seeking.

    0 讨论(0)
  • 2021-01-02 03:46
    <input type="checkbox" name="showAll" id="showAll">Include completed
    

    Will Post a value of "on" or "off".

    This WONT bind to a boolean,

    To receive a boolean value you can use HTML Helper Checkbox Like

    @Html.CheckBox("showAll")
    <label for="showAll" style="display:inline">Include completed</label>
    

    Update:

    If checked the html helper will post back "true,false" and if unchecked as "false"

    You can have this workaround as

    bool MyBoolValue= Convert.ToBoolean(collection["showAll"].Split(',')[0]);
    

    This is because the Html helpers class adds an extra hidden field to save the state of the checkbox

    0 讨论(0)
提交回复
热议问题