[英]ASP.NET MVC: Model Binding and Ajax Request
我有一个按钮:
<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类型可以正常工作。
如何对我的删除操作使用复杂类型?
类DeleteTeamEmployeeInput:
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
整数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"
不是有效的标识符名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.