checkbox oncheck redirect to actionresult in mvc
Asked Answered
E

2

1

I am creating a project in mvc which uses webgrid. In the webgrid I have two columns namely Status and IsActive.

The status column can contain only two values: checked or unchecked.Both these values come from database.

The IsActive column has checkbox which is in checked state if the status is checked in the Status column and vice versa.

I have an actionresult in my controller which checks the status of the particular row and reverses it (i.e) If the status was checked it will change to unchecked and vice versa.This is the code:

public ActionResult Add(string path,string status)
{
    on.Open();
    if (status == "unchecked")
    {
            SqlCommand cmd = new SqlCommand("SpAdRegister1", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@imagepath", path);
            cmd.ExecuteNonQuery();
        }
    }
    else
    {
        SqlCommand cmd = new SqlCommand("SpAddeRegister", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@imagepath", path);
        cmd.ExecuteNonQuery();
    }
    return RedirectToAction("Index", "Ad");
}

In the above code the status is the value of the corresponding Status column and path is the path of the image defined in the database.

The above code should execute when I check/uncheck the checkbox.Also the state of the checkbox should be permanent (i.e) if it was checked it has to remain checked always till i uncheck it.

EDIT This is the way i am getting the value of the path and passing it to the view:

public ActionResult Index()
        {

            SqlCommand cmd = new SqlCommand("select * from Cpecial_Ad_management_tbl where [Partner Name]='"+partname+"' ", con);

            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            List<AddDetailModel> model = new List<AddDetailModel>();
            while (dr.Read())
            {
                model.Add(new AddDetailModel()
                {

                AdName = dr["Ad_name"].ToString(),
                AdType=dr["Ad_type_name"].ToString(),
                PartnerName=dr["Partner Name"].ToString(),
                hrefurl=dr["Ad_url"].ToString(),
                startDate=dr["Start_date"].ToString(),
                endDate = dr["End_date"].ToString(),
                tagName = dr["Tag"].ToString(),
                AdPath= dr["Ad_image_path"].ToString(),
                Status = dr["Status"].ToString()              
                });
            }
            dr.Close();

            return View(model);
        }

Here the AdPath is the path which i am using in my another controllers.

EDIT code for view:

@model IEnumerable<EShopPartnerSetting.Models.AddDetailModel>

@{
    var grid1 = new WebGrid(source: Model.Where(m => m.AdType == "bottom_banner").ToArray(),
                                              defaultSort: "First Name",
                                              rowsPerPage: 2, fieldNamePrefix: "wg_",
                                              canPage: true, canSort: true,
                                              pageFieldName: "pg", sortFieldName: "srt"
                                              );
    var grid2 = new WebGrid(source: Model.Where(m => m.AdType == "side_banner_bottom").ToArray(),
   defaultSort: "First Name",
   rowsPerPage: 2, fieldNamePrefix: "wg_",
   canPage: true, canSort: true,
   pageFieldName: "pg", sortFieldName: "srt"
   );
    var grid3 = new WebGrid(source: Model.Where(m => m.AdType == "side_banner_top").ToArray(),
    defaultSort: "First Name",
    rowsPerPage: 2, fieldNamePrefix: "wg_",
    canPage: true, canSort: true,
    pageFieldName: "pg", sortFieldName: "srt"
    );  
}
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Ad Management</title>
    <link href="../../CSS/AdminLayStyle.css" rel="stylesheet" type="text/css" />
    <link href="../../CSS/Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <link href="../../CSS/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
    <link href="../../CSS/Content/themes/base/jquery.ui.base.css" rel="stylesheet" type="text/css" />
    <link href="../../CSS/Content/themes/base/jquery.ui.dialog.css" rel="stylesheet"
        type="text/css" />
    <script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <script type="text/javascript">
        $('input[name=chk]').change(function () {

            var status;
            if ($('input[name=chk]').is(':checked')) {
                status = "checked"
            } else {
                status = "unchecked"
            }
            var path = @Model.AdPath;
            alert(status);
                sendRequest(path, status);
        });
function sendRequest(path, status) {
    $.get('@Url.Action("Add","Ad")' + '?path=' + path + '&status=' + status, function(){
       alert('calling the actionresult add');
    }).done(function(){
       //show an update on the page
    });
}

    <style type="text/css">
       some style
    </style>
</head>
<body>
    @using (Html.BeginForm(new { id = "target" }))
    {
        @Html.ValidationSummary(true)
        <table width="960" border="0" align="center" cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    <div class="maindiv1">
                        <div class="hd">
                            <h3>
                                Ad Management</h3>
                        </div>
                        <div class="bd">
                            <table align="center" cellpadding="0" cellspacing="0" width="100%">
                                <tr>
                                    <td>
                                        <input id="new" type="button" value="Create New Ad" style="color: #FFFFFF; background-color: #1688C6;" />
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td align="center">
                                        <span><div style="background-color:#4FA6E4; width:680px;" >Bottom Banner</div></span>
                                        @grid1.GetHtml(tableStyle: "listing-border", headerStyle: "gridhead", footerStyle: "paging", rowStyle: "td-dark", alternatingRowStyle: "td-light",
                            columns:
                                grid1.Columns(
                                grid1.Column("AdName", "Ad/Campaign", style: "colProductid"),
                                grid1.Column(header: "Ad", format: @<text><img src="@item.AdPath"  id="adimg"  alt="YourText" title="Ad Image"  width:"50px" height="50px"></text>, style: "colAdimage"),
                                grid1.Column("startDate", "Start Date", style: "colCategoryID"),
                                grid1.Column("endDate", "End Date", style: "colCategoryID"),
                                  grid1.Column(header: "IsActive", format: @<text><input name="chk" class="chk2"(@item.Status)" type="checkbox"  @item.Status/></text>, style: "colOperation"),
                                  grid1.Column(header: "Edit", format: @<text><a id="@item.AdName" class="clk"><img
                                    src="../../Images/edit.png" class="asa" width="25px" height="25px" alt="" style="border: none;" /></a></text>, style: "colOperation"),
                                 grid1.Column(header: "Delete", format: @<text><a href="@Url.Action("Delete", "Ad", new { aname = item.AdName, apath = item.AdPath, status = item.Status })" onclick="javascript:return ConfirmDelete();"><img
                                    src="../../Images/delete.png" width="20px" height="20px" alt="" style="border: none;" /></a></text>, style: "colOperation"),
                                 grid1.Column(header: "Status", format: @<text>
                                        </text>, style: "colOperation")
                                         ), mode: WebGridPagerModes.All)
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        &nbsp;
                                    </td>
                                </tr>
                                <tr>
                                    <td width="100%" align="center">
                                        @* <input id="Submit1" type="submit" value="submit" />*@
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <script type="text/javascript">
                            function ConfirmDelete() {
                                return confirm("Are you sure you want to delete this?");
                            }
                        </script>
                    </div>
                    @* <a id="clk">click here</a>*@
                    <div id="dialog" title="Edit" style="overflow: hidden;">
                    </div>
                    <div id="newdialog" title="Create" style="overflow: hidden;">
                    </div>
                </td>
            </tr>
        </table>
    }
</body>
</html>

code for model:

 public class AddDetailModel
    {

    public string AdName { get; set; }
    public string AdType { get; set; }
    public string PartnerName { get; set; }
    public string hrefurl { get; set; }
    public string startDate { get; set; }
    public string endDate { get; set; }
    public string tagName { get; set; }
    public string AdPath { get; set; }
    public string BannerPath { get; set; }
    public string Status { get; set; }
    }

So essentially the question is how to redirect to actionresult on checkbox click and how to make the status of the checkbox (checked/unchecked) based on some value from database?

Any help would be greatly appreciated.

Eslinger answered 11/3, 2013 at 6:10 Comment(0)
D
1

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.

Diacaustic answered 11/3, 2013 at 7:11 Comment(5)
actually the path is a parameter in the model. I am getting the value from the database and passing it onto view.I have added the code to explain it.Eslinger
Well you can write that out to the page using razor @Model.Path and grab it from there. If you want to redirect to the page go with darins answer, otherwise this will hit the action and stay on the same page.Diacaustic
I dont want to redirect to any page.I want it to redirect to the actionresult and come back to the same page. Also if i pass [email protected] i am getting an errorEslinger
Well one way would be to hit the action result asynchronously and update the page like above. What error are you receiving?Diacaustic
it is showing "Expected expression" also i am passing the model like this : @model IEnumerable<PartnerSetting.Models.AddDetailModel>Eslinger
H
1

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>
Harass answered 11/3, 2013 at 7:13 Comment(4)
I don't want to redirect my page.As you can see from my code, after the Add method is executed the user is redirected back to the same pageEslinger
Yes, that's normal and is what will allow you to update the table data.Harass
Ok..now i am having issues giving the path.I give [email protected] but i am getting expected expression error.I have updated the question with the code for viewEslinger
I do not see in your code where you are using @Model.AdPath. Also this will only work if your model is not an IEnumerable<Something>. If it is then you need to get the path of the current row and you can only do that using javascript because it is only on the client side that you know which row was clicked. You cannot be hardcoding the path value with @Model.Path. You should use a jQuery selector to retrieve this value from the corresponding column of the table row. You could use the .closest() method to get the corresponding row (<tr>) and then descend into the correct column.Harass

© 2022 - 2024 — McMap. All rights reserved.