2011-01-19 119 views
0

我有一个按钮:ASP.NET MVC:模型绑定和Ajax请求

<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对象时,它始终为空。简单的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); 
} 

回答

1

你一定要通过返回从你点击回拨或您的AJAX请求甚至可能没有足够的时间错误的取消默认操作结果在重定向之前执行。至于发送整个对象(只包含一个TeamEmployee整数propertry)而言,你可以这样做:

// 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"在你的锚是无效的标识符名称。

+1

非常感谢你Darin!据我了解,我需要添加路由数据到网址。我现在的问题是如何使这个“新{TeamEmployee =”2“}”通用:)。我会更新我的帖子。 – Rookian 2011-01-20 20:42:10