问题
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>
</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>
</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.
回答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>
回答2:
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.
回答3:
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!
来源:https://stackoverflow.com/questions/15332225/checkbox-oncheck-redirect-to-actionresult-in-mvc