1
基本上就是我想要做的是:調用js函數的代碼隱藏(不作爲startupScript)
- 點擊一個按鈕來刪除記錄。
- 刪除記錄如果某個特定列(位置)爲空(此操作已完成且工作正常)
- 刪除記錄,但如果特定列不爲空,請要求用戶確認。
所以第3步是棘手的部分。使用AJAX,我將調用您在下面看到的deleteChannel(url)
,它在代碼隱藏中調用正確的方法。現在,這裏是棘手的部分:
if (channel != null && channel.Location != null)
{
// How do I do this? (Notice that this is code-behind)
ShowDialogThatAsksUserToConfirm()
}
代碼:ShowDialogThatAsksUserToConfirm()
需要調用回客戶端說「的位置列不爲空」,並等待用戶說反正刪除或取消。
我有這樣的代碼,將調用的方法在後面的代碼:
function deleteChannel(url) {
$.ajax({
url: url,
type: "POST",
cache: false,
contentType: 'application/html; charset=utf-8',
data: $("form").serialize(),
dataType: 'html',
success: function (msg) {
showDialog('successDiv');
},
error: function (msg) {
alert("error");
showDialog('errorDiv');
}
});
}
而且ShowDialog的(......)看起來是這樣的:
function showDialog(divID) {
$("#" + divID).dialog({
show: "clip",
hide: "clip",
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
}
代碼隱藏看起來是這樣的:
[HttpPost]
public ActionResult DeleteChannel(int id)
{
var statusCode = new HttpStatusCode();
using (var context = new MaaneGrisContext())
{
var channel = context.Channels.FirstOrDefault(x => x.ID == id);
if (channel != null && channel.Location != null)
{
if (Confirmation()) //The Confirmation() method not implemented yet, but it should ask user to confirm
{
context.Channels.Remove(channel);
context.SaveChanges();
List<ChannelModel> updatedChannelList = new List<ChannelModel>();
context.Channels.AddRange(context.Channels);
return View("ChannelDetails", updatedChannelList);
}
}
}
這裏查看:
<table style="border: ridge 1px">
<tr>
<th>Name</th>
...
</tr>
@{
foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(m => item.ChannelName)</td>
<td>@Html.DisplayFor(m => item.Description)</td>
<td>@Html.DisplayFor(m => item.Unit)</td>
<td>@Html.DisplayFor(m => item.Location.StableName)</td>
<td>@Html.DisplayFor(m => item.CreationDate)</td>
<td>@Html.DisplayFor(m => item.LastEdited)</td>
<td>@Html.DisplayFor(m => item.ExtraNote)</td>
<td><a href="@Url.Action("CopyChannel", "Channel", new { id = item.ID })"><span class="glyphicon glyphicon-copy"></span></a></td>
<td><a href="@Url.Action("EditChannel", "Channel", new { id = item.ID })"><span class="glyphicon glyphicon-edit"></span></a></td>
<td><a href="#" onclick="deleteChannel('@Url.Action("DeleteChannel", "Channel", new { id = item.ID })')">
<span class="glyphicon glyphicon-remove"></span></a>
</td>
</tr>
}
}
</table>
<br/><br/>
<div style="display: none;">
@* @{ Html.RenderPartial("_CreateChannel"); } *@
</div>
<h5>@Html.ActionLink("Opret en ny kanal", "RegisterChannel", "Channel")</h5>
<div id="cautionDiv" title="Bekræft sletning" style="display: none;">
<p style="color: red;">The channel has a location. Are you sure you want to delete?</p>
</div>
<div id="successDiv" title="Info" style="display: none;">
<p style="color: green;">Deleted</p>
</div>
這只是我的方法,而不是終點,如果有更好的解決方案,請讓我知道
將你的「webapi」方法分解爲兩個不同的方法,一個檢查是否可能執行處理並向客戶端返回一些標誌,另一個可毫無疑問地執行該操作? –