Skip to content
Advertisement

Why is my on click event not working? (ASP.NET MVC)

I have a checkbox in my view, with an onclick event which sends the checkboxes ID to an action result in my controller (using Ajax). However, after running a breakpoint on the passed value within my controller, it seems as thou nothing is happening when i click on the checkbox? Why could this be?

My checkbox:

@using (Html.BeginForm("ItemsEdit", "Items", FormMethod.Post))
{

            <input id = "@dataLineItem.Split(Model.ItemList.delimiterChar)[0]" type = "checkbox" value = "true" name = "Remember" onclick = "sendCheckId(this.id)"/>

            <input type = "hidden" value = "false" name = "Remember" />

}

Jquery for sending the value to my ActionResult:

function sendCheckId(checkedId) {
        var sentId = checkedId;
        $.post("Items/ItemsEdit/", { sendIdToAction: sentId })
    }

And finally my ActionResult within my “Items” controller:

public ActionResult ItemsEdit(string sendIdToAction, bool Remember)
{
            string itemCheck = "true";
            var path = "~/App_Data/Item.txt";
            var originalLines = System.IO.File.ReadAllLines(Server.MapPath(path));
            var updatedLines = new List<string>();

            foreach (var line in originalLines)
            {
                string[] infos = line.Split(',');

                if(infos[0] == sendIdToAction)
                {
                    infos[3] = Remember.ToString();
                }

                updatedLines.Add(string.Join(",", infos));
            }

            System.IO.File.WriteAllLines(Server.MapPath(path), updatedLines);

            return View();
}

What i am trying to do is pass the value of “Remember”, which if i am correct, would be either true or false depending on whether the checkbox is ticked or not.

Advertisement

Answer

Because you have bool Remember parameter, you need send Remember parameter, and your URL miss “/”, update your function as

function sendCheckId(checkedId) {
        var sentId = checkedId;
        $.post("/Items/ItemsEdit/", { sendIdToAction: sentId, Remember: false });
}

If you don’t want to put Remember parameter in POST method, you can set default value in action controller as

public ActionResult ItemsEdit(string sendIdToAction, bool Remember = false)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement