要實現的效果是,當點擊checkbox時,跳轉到Action中
CheckBox實例:
View界面:
@Html.CheckBox("prd.IsChecked", Model.IsChecked,new { data_url = Url.Action("Save", "Home"),ProductID= Model.ProductID })
注釋:new { data_url = Url.Action("Save", "Home"),ProductID= Model.ProductID },要傳輸的數據
頁面生成:
<input name="prd.IsChecked" id="prd_IsChecked" type="checkbox" value="true" data-url="/Home/Save" productid="77">
<input name="prd.IsChecked" type="hidden" value="false">
注釋:MVC中Checkbox控件在頁面顯示為兩條數據
JS:
<script src="~/Scripts/jquery-1.4.1.js"></script>
//引用JS文件
<script type="text/javascript">
$(function () {
$(":checkbox").change(function () {
$.ajax({
url: $(this).attr('data-url'),
type: 'POST',
data: { IsChecked: $(this).attr('checked'), ProductID: $(this).attr('ProductID') }
});
});
});
</script>
//$(this).attr('checked'),點擊復選框后的當前狀態,勾選后界面HTML中會顯示checked=‘checked’,獲取當前復選框狀態(true,false)
//$(this).attr() :this當前對象,attr()當前對象中的元素
Controller:
[HttpPost]
Public ActionResult Save(bool IsChecked,int ProductID)
{
//選中,取消事件
}
//(bool IsChecked,int ProductID):參數名稱要與Ajax中的參數名稱相對應
