javascript - 如何从 javascript 打开操作调用的 View 结果

标签 javascript asp.net-mvc razor

我正在使用 ASP.Net mvc 4 进行开发。我的索引 View 中有一个删除功能。在用户继续删除项目之前,这是要执行的步骤

  1. 弹出一个确认对话框,使用 JavaScript 获取"is"或“否”答案。

  2. 如果用户说"is",我会从 Controller 调用删除操作

  3. 删除操作从数据库中删除项目

  4. 删除操作返回 'RedirectToAction ("Index");'

  5. ..假设 View 将使用最新更新进行更新

第 5 步是我的问题..它不起作用

这是我的代码

删除按钮

<a href="@Url.Action("DeleteFile", new { id = @item.Id })"  
    onclick = "return confirm2delete(this);"
    class="btn btn-danger btn-sm" 
    data-toggle="tooltip" title="Delete File">
    <i class="fa fa-trash-o"></i>
</a>

JavaScript

function confirm2delete(obj)
{      
    deleteLinkObj = $(this);
    w2confirm("Are sure to delete this file ?")
    .yes(function () {
        $.get(obj.href, function (data) {
            alert(data); // i checked ..this return the html page created from the delete action
            window.open (data); // not the right approach ???
        });

    })
    .no(function () {
        alert("no");
        result = false;
    });
    return false;
}

我的 Controller 中的删除操作

public ActionResult DeleteFile(int id)
{
    FileUpload f = db.FileUploads.Find(id);
    try
    {                
        FileInfo dfile = new FileInfo(f.fileUrl);
        if (dfile.Exists) { dfile.Delete(); }
        fileUrl = f.FileUrl.Replace("Images/Uploads", "Images/Thumbnails");
        FileInfo thumbnail= new FileInfo(fileUrl);
        if (thumbnail.Exists) { thumbnail.Delete(); }
        db.FileUploads.Remove(f);
        db.SaveChanges();
    }
    catch (Exception ex)
    {
    }
    return RedirectToAction("Index");  // or may i should return something else to make it work in javascript ???
}

希望大家能帮帮我。我几天来一直在寻找和尝试达到这个水平,我觉得是时候寻求一些帮助了。再多一点点。快到了。

最佳答案

Ajax 调用停留在同一页面中,因此调用 return RedirectToAction("Index"); 是没有意义的(它不会重定向)。无论如何,都没有必要返回新 View 。相反,如果 Controller 成功删除了该项目,您可以从 DOM 中删除现有元素。您尚未显示您的 View ,但假设您有一个表,其中一行可能类似于

<tr>
  <td>the name of the file</td>
  <td>the delete link</td>
</td>

然后您可以在“删除”链接所在的位置使用以下内容

<td><button type="button" class="delete" data-id="@item.Id">Delete</button></td>

关键点是 classdata-id 属性 - 修改其余部分以适合您的显示,但删除 onclick 属性(停止用行为污染你的标记并使用 unobtrusive javascript - 这是 21 世纪!)

然后是脚本

var url = '@Url.Action("DeleteFile")';
$('.delete').click(function() {
  var id = $(this).data('id');
  var row = $(this).closest('tr'); // modify if the containing element is not a <tr>
  w2confirm("Are sure to delete this file ?")
    .yes(function () {
      $.post(url, { id: id }, function(response) { // its a POST, not a GET!
        if (response) {
          row.remove(); // remove the row
        } else {
          // Oops, something went wrong
        }
      }).fail(function (response) {
        // Oops, something went wrong
      });
    })
    .no(function() {
      alert("no");
    });
});

请注意,如果您使用 jquery 1.9+ 版本,则不需要 $.post() 函数中的 else block ,因为 return Json(null);下面方法中的将进入.fail()回调

然后在 Controller 中,返回json表示该项已成功删除

[HttpPost]
public ActionResult DeleteFile(int id)
{
  FileUpload f = db.FileUploads.Find(id);
  try
  {                
    ....
    db.SaveChanges();
    return Json(true); // signal success
  }
  catch (Exception ex)
  {
    return Json(null); // signal failure
  }
}

关于javascript - 如何从 javascript 打开操作调用的 View 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386451/

相关文章:

javascript - 使用 parseJSON 解析 JSON 字符串时出错

javascript - jQuery 在 ajax 调用后,具有相同 Id 的事件停止工作

javascript - JS/jQuery - 如果语句没有 "return"

css - MVC5 Vanilla 布局未显示

asp.net-mvc - ASP.Net MVC4 HandleError 未渲染指定 View

asp.net-mvc-4 - 使用 @Url.Content ("~"是否有好处)

javascript - 用于将缩进行转换为代码块的正则表达式

asp.net - 即使在 FormsAuthentication.SignOut() 之后 User.IsOnline = true

c# - asp.net mvc razor foreach循环将id添加到div

asp.net-mvc - ASP MVC 多对多关系 - 从关联表中检索数据