checkbox oncheck redirect to actionresult in mvc

◇◆丶佛笑我妖孽 提交于 2019-12-08 04:00:30

One possibility is to use javascript and subscribe to the change event of the checkbox and then redirect to this controller action. For example if you are using jQuery you might try something like this:

<script type="text/javascript">
    $(function() {
        $('table input[type="checkbox"]').change(function() {
            // determine the value of the status parameter based on whether
            // the checkbox that we clicked on was checked or unchecked
            var status = $(this).is(':checked') ? 'unchecked' : 'checked';

            // it's not quite clear where the path parameter should come from
            // but if it shown somewhere in the table you could use a jQuery 
            // selector to retrieve it
            var path = ...;

            // calculate the url to redirect to
            var url = '@Url.Action("Add")' + 
                      '?path=' + encodeURIComponent(path) + 
                      '&status' + encodeURIComponent(status);

            // redirect
            window.location.href = url;
        });
    });
</script>

You can do it with javascript asynchronously if you modify your Add action result to return some type of success message with a json result:

public ActionResult Add(string path, string status)
{
    //Execute your stored procedure.

    //If successful 
    return Json(new { success = true }, JsonRequestBehaviours.AllowGet);
}

$('input[name=CheckBoxName]').change(function(){
    var path = //as your model type is IEnummerable<AddDetail> you will have to select it using javascript
    var status = $(this).is(':checked') ? 'unchecked' : 'checked';
    sendRequest(path, status);
});

function sendRequest(path, status) {
    $.get('@Url.Action('Add')' + '?path=' + path + '&status=' + status, function(){
       alert('calling the actionresult add');
    }).done(function(){
       //show an update on the page
    });
}

On another note, consider abstracting your data access code to a different layer.

I finally figured out the answer. I used the onchange event of the checkbox to call a javascript function. Here is the code:

grid1.Column(header: "IsActive", format: @<text><input name="chk" class="chk2" value="@item.AdPath" type="checkbox" onchange="adchange('@item.AdType','@item.AdPath','@item.Status')"  @item.Status/></text>, style: "colOperation"),

and the javascript function is :

     function adchange(id, path, status) {

                $.get('@Url.Action("Add","Ad")' + '?ids=' + id + '&path=' + path + '&status=' +status);
}

Thanks to gdp and Darin for their help with the javascript code!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!