我试图使用jQuery AJAX将按钮绑定到控制器中的动作。我这样做,但它没有用。
@model InventoryTest.MyModel
@using (Html.BeginForm(new { id = "itemTypeForm" }))
{
<input type="submit" value="Delete" id="deleteButton" class="button btn btn-danger" />
<!-- other form elements... -->
}
在控制器中我有:
[HttpPost]
public ActionResult Delete(MyModel myModel )
{
if (myModel != null);
// do something...
return(view);
}
AJAX代码是:
$("#deleteButton").on('click', function (e) {
e.preventDefault();
if (formIsValid) {
$.ajax({
url: '/Home/Delete',
type: 'POST',
data: form.serialize()
}).done(function (data) {
if (data.success) {
alert("sucsess")
} else {
alert("error");
}
});
}
})
编辑:
$("#deleteButton").on('click', function (e) {
e.preventDefault();
$.ajax({
url: '/Home/Delete',
type: 'POST',
**data:$("#itemTypeForm").serialize()**
}).done(function (data) {
if (data.success) {
alert("sucsess")
} else {
alert("error");
}
});
})
我更改了AJAX部分以使用其id访问表单,它现在调用操作但我收到错误消息并且返回的模型对象为空。
答案 0 :(得分:0)
您应该将当前Id包装在名称必须匹配的隐藏元素中。
在模型中说出您的删除ID名称是ProjectID
,然后 - 强>
@using (Html.BeginForm(new { id = "itemTypeForm" }))
{
@Html.HiddenFor(m=>m.ProjectID) //getting from above model
<input type="submit" value="Delete" id="deleteButton" class="button btn btn-danger" />
<!-- other form elements... -->
}
然后 -
[HttpPost]
public ActionResult Delete(MyModel myModel )
{
int projectID = myModel.ProjectID //just to make sure if id is coming
if (myModel != null);
// do something...
return(view);
}
这样你可以让它发挥作用。
答案 1 :(得分:0)