2011-01-19 99 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