ASP.NET MVC:模型绑定和AJAX请求
-
12-10-2019 - |
题
我有一个按钮:
<a id="2" class="modalInput specialbutton" href="/Employee/Delete/2" rel="#yesno"><img src="/Content/Images/application_delete.png" alt="Delete" /></a>
该按钮的JavaScript:
var buttons = $("#yesno button").click(function (e) {
var yes = buttons.index(this) === 0;
if (yes) {
$.ajax({
url: overlayElem.attr('href'),
success: function (data) {
$("#gridcontainer").html(data);
}
});
}
});
删除操作:
public ActionResult Delete(int id)
{
DeleteTeamEmployeeInput deleteTeamEmployeeInput = new DeleteTeamEmployeeInput { TeamEmployee = id };
return Command<DeleteTeamEmployeeInput, TeamEmployee>(deleteTeamEmployeeInput,
s => RedirectToAction<EmployeeController>(x => x.Index(1)),
f => RedirectToAction<EmployeeController>(x => x.Index(1)));
}
问题是 id
范围。直接使用会很好 DeleteTeamEmployeeInput
.
public ActionResult Delete(DeleteTeamEmployeeInput deleteTeamEmployeeInput )
{
return Command<DeleteTeamEmployeeInput, TeamEmployee>(deleteTeamEmployeeInput,
s => RedirectToAction<EmployeeController>(x => x.Index(1)),
f => RedirectToAction<EmployeeController>(x => x.Index(1)));
}
当我使用complext对象时,它始终为null。简单的INT类型正常。
如何将复杂类型用于我的删除操作?
类deleteTeamemployeeEinput:
public class DeleteTeamEmployeeInput
{
public int TeamEmployee { get; set; }
}
删除按钮:
public static string DeleteImageButton(this HtmlHelper helper, int id)
{
string controller = GetControllerName(helper);
string url = String.Format("/{0}/Delete/{1}", controller, id);
return ImageButton(helper, url, "Delete", "/Content/Images/application_delete.png", "#yesno", "modalInput", id);
}
解决方案
您绝对需要通过从单击回调中返回false来取消默认操作结果,否则您的AJAX请求甚至可能没有时间在重定向之前执行。至于发送整个对象(仅包含一个 TeamEmployee
整数适当特里)担心您可以做到这一点:
// that selector seems strange as you don't have a button inside your anchor
// but an <img>. You probably want to double check selector
var buttons = $('#yesno button').click(function (e) {
var yes = buttons.index(this) === 0;
if (yes) {
$.ajax({
url: this.href,
success: function (data) {
$("#gridcontainer").html(data);
}
// that's what I was talking about canceling the default action
});
return false;
}
});
然后生成您的锚,使其包括此参数:
<a href="<%: Url.Action("delete", "employee", new { TeamEmployee = "2" }) %>" id="link2" class="modalInput specialbutton" rel="#yesno">
<img src="<%: Url.Content("~/Content/Images/application_delete.png") %>" alt="Delete" />
</a>
现在您可以安全地拥有:
public ActionResult Delete(DeleteTeamEmployeeInput deleteTeamEmployeeInput)
{
...
}
评论: id="2"
在您的锚点中,不是有效的标识符名称。
不隶属于 StackOverflow