Для достижения желаемой функциональности я использую ActionLink с параметром:
@foreach (var widget in widgets){
Widget @widget.Id @Html.ActionLink("Delete", "Home", new { id = @widget.Id})<br />
}
А в вашем контроллере:
public ActionResult Delete(int id)
{
//Get your widget ID here and do the deletion as required.
return View("Your View");
}
Вы можете оформить свой ActionLink так, как требуется:
@Html.ActionLink("Delete", "Home", new { id = @widget.Id},new { @style="your style goes here" });
EDIT :
Вы можете использовать AJAX, если хотите отправить свои данные на контроллер. Конкретно в вашем случае я покажу вам пример:
@foreach (var widget in widgets){
Widget @widget.Id : <a href="#" data-id="@widget.Id" onclick="confirmDelete(this)"></a><br />
}
В тебе AJAX:
function confirmDelete(event) {
var recordToDelete = $(event).attr("data-id"); //Get your current widget id here
if (confirm("Are you sure you want to delete this widget") == true) {
//Prepare our data
var json = {
id: recordToDelete
};
$.ajax({
url: '@Url.Action("Delete", "Home")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json) },
success: function (data) {
if(data == "success") {
alert("Successfully deleted selected widget");
location.reload();
}
},
error: function (data) {
alert("Could not delete selected widget. Please try again!");
},
});
}
};
И, наконец, в вашем контроллере:
//Delete a widget based on the ID that you get from your View
[HttpPost]
public JsonResult Delete(string json)
{
var serializer = new JavaScriptSerializer();
try
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string id = jsondata["id"];
if(id != "")
{
int getid = Convert.ToInt32(id);
//Call your db or your logic to delete the file
DatabaseAccess data = new DatabaseAccess();
string result = data.DeleteFile(getid);
if(result.Equals("Success"))
{
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("fail", JsonRequestBehavior.AllowGet);
}
}
else
{
return Json("notfound", JsonRequestBehavior.AllowGet);
}
}
catch
{
return Json("dberror", JsonRequestBehavior.AllowGet);
}
}