[英]Dynamically add/remove table rows in a wizard
我當前在我的應用程序中使用此向導 。
在我的步驟之一中,我需要從表中添加和刪除項目。 添加功能可以正常工作。 但是我無法使Delete功能起作用。 我在網上搜索了SO和其他資源,找不到解決方案。
這是我到目前為止的內容:
向導步驟2表:
<table id="LibList" class="table table-responsive table-striped">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Step3.Liabilities[0].Types)
</th>
<th>
@Html.DisplayNameFor(model => model.Step3.Liabilities[0].Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Step3.Liabilities[0].Teams)
</th>
<th>
<label>Delete</label>
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Step3.Liabilities) {
Html.RenderPartial("_LibListItem", item);
}
</tbody>
</table>
部分視圖:
<tr>
<td>
@Html.DropDownListFor(model => model.Type, Model.Types, new { @class = "selectpicker form-control", id = string.Format("{0}_{1}", "TYPE", Model.ID) })
</td>
<td>
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", id = string.Format("{0}_{1}", "NAME", Model.ID) })
</td>
<td>
@Html.TextBoxFor(model => model.Teams, new { @class = "form-control", @type = "currency", id = string.Format("{0}_{1}", "TERMS", Model.ID) })
</td>
<td>
@Ajax.ActionLink("Delete", "Delete", "QuestionWizard", new { id = Model.ID },
new AjaxOptions() {
HttpMethod = "Delete",
Confirm = "Are you sure you want to delete this record?",
OnComplete = "function() { $(this).parent().parent().remove() }"
},
new { @class = "btn btn-primary" })
</td>
添加和刪除操作:
public ActionResult AddRow() {
LiabilityModel lib = new LiabilityModel();
try {
if (LiabilitySessionState.Count == 0) {
lib.ID = 1;
} else {
lib.ID = LiabilitySessionState.LastOrDefault().ID + 1;
}
LiabilitySessionState.Add(lib);
return PartialView("_LibListItem", lib);
} catch (Exception ex) {
System.Web.HttpContext.Current.Application.Add("LASTERROR", ex);
return RedirectToAction("Index", "Error");
}
}
public void Delete(int Id) {
try {
if (LiabilitySessionState.Count > 0) {
LiabilitySessionState.RemoveAll(item => item.ID == Id);
}
} catch (Exception ex) {
System.Web.HttpContext.Current.Application.Add("LASTERROR", ex);
RedirectToAction("Index", "Error");
}
}
public List<LiabilityModel> LiabilitySessionState {
get {
if (Session["LiabilityModel"] == null) {
return LiabilitySessionState = new List<LiabilityModel>();
} else {
return Session["LiabilityModel"] as List<LiabilityModel>;
}
}
set {
Session["LiabilityModel"] = value;
}
}
腳本:
<script type="text/javascript">
$(document).ready(function () {
$('.add-button').click(function () {
var action = "/QuestionWizard/AddRow";
$.ajax({
url: action,
cache: false,
success: function (result) {
$("#LibList tbody").append($(result));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
})
$(".remove-button").click(function () {
$(this).parents().parent().remove();
return false;
});
});
現在,“刪除操作”將返回空白頁,因為我沒有返回視圖。 但是,我不確定該返回什么視圖。
請幫忙!
提前致謝。
首先,您的Delete()
方法正在更改數據,因此它必須是POST,而不是GET( @Ajax.ActionLink()
是)。 接下來,您的“刪除鏈接”沒有class="remove-button"
因此$(".remove-button").click(function () {
不會做任何事情。因為您已經在使用jquery ajax方法添加項(請參閱無論如何,使用Ajax幫助器似乎毫無意義(您只是通過加載jquery.unobtrusive-ajax.js
文件增加了額外的開銷)。
將局部元素的最后一個<td>
元素更改為
<td>
<button type="button" class="remove-button" data-id=@Model.ID>Delete</button>
</td>
然后在主視圖中,使用以下腳本(請注意,您需要事件委托,以便可以刪除動態添加的項目)
var url = '@Url.Action("Delete", "YourControllerName")';
$('#LibList').on('click', .remove-button, function() {
var row = $(this).closest('tr');
var id = $(this).data('ID');
if (id) { // assumes property ID is nullable, otherwise may need to test if id != 0
$.post(url, {ID: id }, function(response) {
if(response) {
row.remove();
} else {
// Oops - display message?
}
});
} else {
// its a new row so it has not been saved yet - just delete the row
row.remove();
}
});
和控制器方法應該看起來像
[HttpPost]
public JsonResult Delete(int ID)
{
// delete the item
return Json(true); // or if an exception occurred, return(null) to indicate failure
}
旁注:
AddRow()
和Delete()
方法都包含return RedirectToAction()
語句。 您正在進行的ajax調用停留在同一頁面上,因此RedirectToAction()
是毫無意義的(永遠不會執行) name
屬性(沒有索引器)不會綁定到您的Liabilities
集合)。 您需要在for
循環中生成現有項目,並為Index
屬性包括隱藏的輸入,並使用客戶端模板生成新項目; 或者如果使用局部視圖,則需要使用BeginCollectionItem
幫助器。 此答案顯示了如何同時使用這兩種技術。 id
屬性。 代替使用id = string.Format("{0}_{1}", "NAME", Model.ID)
,只需使用id=""
渲染不id = string.Format("{0}_{1}", "NAME", Model.ID)
and id
屬性的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.