我想允许用户在他们认为“良好”的每个项目旁边选中一个框,并允许他们通过两次单独按下按钮来删除项目列表。如何将数据传递到相应的控制器动作?
我有一个包含布尔字段的IEnumerable对象列表。
Public class fruit
{
public string Name { get; set;}
public bool IsGood {get; set:}
}
我正在这样的表格中显示此内容:
@model IEnumerable<Fruit>
<table>
<thead>
<tr>
<th>Good?</th>
<th>Name</th>
</tr>
</thead>
@foreach (var item in Model)
{
<tbody>
<tr>
<td><input type="checkbox" class="checkbox" value="@item.IsGood" /></td>
<td>Item.Name</td>
</tr>
<tbody>
</table>
}
<input class="btn btn-primary" type="submit" name="Update" id="Update" value="Update" />
<input class="btn btn-danger" type="submit" name="Delete" id="Delete" value="Delete" />
这怎么办?
答案 0 :(得分:1)
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.3.0</version>
</dependency>
@model IEnumerable<Fruit>
<table class="tblFruitDetail">
<thead>
<tr>
<th>Good?</th>
<th>Name</th>
</tr>
</thead>
@foreach (var item in Model)
{
<tbody>
<tr>
<td><input type="checkbox" class="checkbox" value="@item.IsGood" id="@item.FruitId"/></td>
<td>Item.Name</td>
</tr>
<tbody>
}
</table>
<input class="btn btn-primary" type="submit" name="Update" id="btnUpdate" value="Update"/>
<input class="btn btn-danger" type="submit" name="Delete" id="btnDelete" value="Delete"/>
var fruitIds = ",";
var checkboxes = document.querySelectorAll('.tblFruitDetail input[type="checkbox"]')
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function(e) {
fruitIds += e.target.id
})
});
$("#btnDelete").click( function(){
$.ajax({
type:'POST',
url:'/HomeController/DeleteFruitsById',
data: fruitIds,
dataType:'json',
success:function(result){
// do something on success..
},
error: function(err){
// handle error here..
}
});
});
答案 1 :(得分:1)
您单击的按钮名称将被发回到服务器。如果找到Request [“ Update”],则提交了Update按钮。如果找到Request [“ Delete”],则单击Delete按钮。然后,您只需决定要删除还是更新操作方法即可。
您可以做类似的事情
public ActionResult EditFruits(IEnumerable<Fruit> model)
{
if(this.Request.Form.AllKeys.Contains("Delete"))
DeleteSelectedFruits(model);
else if(this.Request.Form.AllKeys.Contains("Update"))
UpdateSelectedFruits(model);
return Wherever you want to go.
}