gpt4 book ai didi

jquery - MVC 3 在数据库中保存复选框状态

转载 作者:行者123 更新时间:2023-12-01 07:18:50 25 4
gpt4 key购买 nike

我有一个问题,希望有人有时间看看。我的 mvc 3 测试项目中有 TableView 。表格里面有一个复选框。我试图在每次单击复选框时保存该复选框。我尝试使用java脚本,尝试使用互联网上的大量示例,但仍然没有运气。有人可以帮忙吗? :)

这是我的观点:

@foreach (var item in Model)
{
<tr>

<td>
@Html.DisplayFor(modelItem => item.date)
</td>

<td>
@Html.DisplayFor(modelItem => item.Name)
</td>

<td>
@Html.DisplayFor(modelItem => item.section)
</td>
<td>

@Html.CheckBoxFor(modelItem => item.check, new { onclick = "SomeMethod(this)" });

</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.idImovine })

</td>
</tr>
}

</table>


<script type="text/javascript">

function SomeMethod(checkboxInput) {

$.ajax({
type: 'POST',
url: 'Home/Action',
data: { newValue: checkboxInput.checked },
success: success,
dataType: 'json'
});
}

</script>

这是我的 Controller

   public JsonResult Action(bool newValue)
{

var model = con.pro.Single(r => r.id == id);


TryUpdateModel(model);
con.SubmitChanges();

return Json(true)


}

我正在使用 linq to sql 来访问数据库。有人可以告诉我我做错了什么吗,我的目的是在单击复选框时将其保存在 dv 中,但是在来自 View 的表格中单击该复选框,并且需要将其保存到另一个选项卡中,所以我我猜我也需要传递位于 View 内的 id 以及复选框值。

最佳答案

您可能需要传递复选框所代表的记录的 ID。因此,让我们像这样更新您的 razor 代码。

@foreach (var item in Model)
{
<tr>
<td>
@Html.CheckBoxFor(modelItem => item.check,
new { @id=item.ID, @class="chks"});
</td>
</tr>
}

现在我们将有一些不引人注目的 JavaScript 来监听复选框的点击事件

<script type="text/javascript">
$(function(){

$(document).on("click","input.chks", function (e) {
var _this=$(this);
var isChecked = _this.is(':checked');
$.post("@Url.Action("Update","Home")?id="+_this.attr("id")+
"&newValue="+isChecked,function(data){
// do something with the response
});

});
});

</script>

现在确保您的 Update 方法接受 2 个参数

[HttpPost]
public ActionResult Update(int id,bool newValue)
{
//do your saving here.
return Json(true);
}

关于jquery - MVC 3 在数据库中保存复选框状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15955778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com