我在mvc中创建一个使用webgrid的项目。在webgrid中,我有两列,即状态和 IsActive 。
状态列只能包含两个值:已选中或未选中。这些值均来自数据库。
IsActive列具有复选框,如果在状态列中选中状态,则该复选框处于已检查状态,反之亦然。
我的控制器中有一个actionresult,它检查特定行的状态并将其反转(即)如果状态被选中,它将变为未选中状态,反之亦然。这是代码:
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");
}
在上面的代码中,status是相应Status列的值,path是数据库中定义的图像的路径。
当我选中/取消选中复选框时,上面的代码应该执行。复选框的状态应该是永久性的(即)如果选中它,则必须始终检查它,直到我取消选中它。
修改 这是我获取路径值并将其传递给视图的方式:
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);
}
此处 AdPath 是我在其他控制器中使用的路径。
用于查看的EDIT 代码:
@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>
模型代码:
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; }
}
所以基本上问题是如何在复选框点击时重定向到actionresult以及如何根据数据库中的某些值来设置复选框的状态(选中/取消选中)?
非常感谢任何帮助。
答案 0 :(得分:1)
如果您修改Add动作结果以返回带有json结果的某种类型的成功消息,则可以异步使用javascript:
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
});
}
另一方面,请考虑将您的数据访问代码抽象到另一层。
答案 1 :(得分:1)
一种可能性是使用javascript并订阅复选框的change
事件,然后重定向到此控制器操作。例如,如果您使用的是jQuery,可以尝试这样的方法:
<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 :(得分:1)
我终于找到了答案。我使用复选框的onchange事件来调用javascript函数。 这是代码:
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"),
和javascript函数是:
function adchange(id, path, status) {
$.get('@Url.Action("Add","Ad")' + '?ids=' + id + '&path=' + path + '&status=' +status);
}
感谢gdp和Darin对javascript代码的帮助!