how to get checkbox property to controller

i have a checkbox that are checked based on the value from my xml but how do i then get the value from the view to the controller

my view

 @using (Html.BeginForm("Settings", "Home", FormMethod.Post))
    {
    foreach (SettingsModel setting in Model)
    {
    <input @(Convert.ToBoolean(setting.GSuccess)==true ? "checked='checked'" : string.Empty) type="checkbox" /></td>
    @Html.ActionLink("Gem", "", null, new { @id = "submit" })
    }

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#submit").click(function () {
                document.forms[0].submit();
                return false;
            });
        });
    </script>

my action result

    [AcceptVerbs(HttpVerbs.Post), ActionName("Settings")]
            public ActionResult Save(SettingsModel setting)
            {
                Boolean gSuccess = setting.GSuccess;

                List<SettingsModel> settings = new List<SettingsModel>();
                XmlDocument doc = new XmlDocument();
                doc.Load(Server.MapPath("~/XML/Settings.xml"));
                foreach (XmlNode node in doc.SelectNodes("/Settings/UserSettings"))
                {
                    settings.Add(new SettingsModel
                    {
                        GSuccess = Boolean.Parse(node["GSuccess"].InnerText)
 });
                doc.Save(Server.MapPath("~/XML/Settings.xml"));
            }
                return RedirectToAction("Settings", "Home");
            ;
        }
        }
    }

Upvotes: 0

Views: 366

Answers (2)

omini data
omini data

Reputation: 417

if you wanna pass a value to the controller you can make it more simple with the html helper and it works with your checked value aswell

@Html.CheckBoxFor(x => setting.GSuccess)

Upvotes: 0

Hussein Salman
Hussein Salman

Reputation: 8226

If a checkbox is checked, then the postback values will contain a key-value pairs.

In your razor, add a name for the check box list:

<input @(Convert.ToBoolean(setting.GSuccess)==true ? "checked='checked'" : string.Empty) 
type="checkbox" name="nameOfYourCheckboxList" /></td>

In your controller use the following:

[HttpPost]
public ActionResult Save(FormCollection collection)
{
     if(!string.IsNullOrEmpty(collection["nameOfYourCheckboxList"])
     {
         //do whatever you need here       
     }
}

Alternative solutions: 1 and 2.

Upvotes: 1

Related Questions