如何使用值传递Ajax调用控制器?

时间:2016-06-26 08:50:37

标签: javascript ajax asp.net-mvc

如何从mvc中的'FileStreamResult'中获取ajax到mvc控制器方法的值?我想通过ajax将值从<a href="#" id="fileId">@Model[i].ToString()</a>传递给控制器​​。

控制器

      public ActionResult Index()
    {
        IEnumerable<VmFile> model = _manager.fileName();
        return View(model);
    }
    public ActionResult Upload(HttpPostedFileBase file)
    {
        try
        {
            if (file.ContentLength > 0)
            {

                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/File/"), fileName);
                file.SaveAs(path);
                _manager.UploadFile(file, path.ToString());
            }
            ViewBag.Message = "Upload successful";
            return RedirectToAction("Index");
        }
        catch
        {
            ViewBag.Message = "Upload failed";
            return RedirectToAction("Index");
        }
    }
 public FileStreamResult GetFile(int Id)
{
    string fileName = _manager.FileName(Id);
    string filePath = ConfigurationManager.AppSettings["FilePath"] +  fileName;
    FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
    return File(fs, "application/pdf");
}

文件管理

   public string FileName (int id)
    {
        string fileName = _unitOfWork.FileRepository.Get(r => r.Id ==   id).Select(f => f.Name).First();
        return fileName;
    }

  public IEnumerable<VmFile> fileName()
    {
        var file = _unitOfWork.FileRepository.Get();

        var model = from r in file
                    select new VmFile
                    {
                        Id = r.Id,
                        Name = r.Name,
                        ThanaId =r.ThanaId,
                        RoadId = r.RoadId,
                        Url = r.Url,
                        UpLoadDate = r.UpLoadDate,
                        FCategoryId = r.FCategoryId, 
                        FileType = r.FileType
                    };

        return model;
    }
   public void UploadFile(HttpPostedFileBase file,string path)
    {

        string fName = file.FileName;
        string[] typ = fName.Split('.');//Regex.Split(fName, @".");
       File newFIle = new File
        {
            Name = fName,
            Url = path,
            FCategoryId = 1,
            ThanaId = 23201,
            RoadId = 12,
            FileType = typ[1],
            UpLoadDate = DateTime.Now
        };
        _unitOfWork.FileRepository.Insert(newFIle);
        _unitOfWork.Save();
    }

VmFile

public class VmFile
 {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
    public Nullable<short> BridgeId { get; set; }
    public Nullable<DateTime> UpLoadDate { get; set; }
    public Nullable<double> FromChain { get; set; }
    public Nullable<double> ToChain { get; set; }
    public string FileType { get; set; }
    public Nullable<int> FCategoryId { get; set; }
    public Nullable<int> ThanaId { get; set; }
    public Nullable<int> RoadId { get; set; }
 }

查看

  @model IEnumerable<RSDMS.ViewModel.VmFile>
@{
Layout = null;
}
 <html>
 <head>
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    </head>

    <body>
        <div id="header" class="container">
            <h2>Document Module</h2>
            <div class="panel panel-default">
                <div id="h2" class=" panel panel-primary "><h4       id="h4">Document Type</h4></div>
                <div id="form" class=" panel-body">
                    <form role="form">
                        <label class="checkbox-inline">
                            <input type="checkbox" value="">A-Road Related
                        </label>
                        <label class="checkbox-inline">
                            <input type="checkbox" value="">B-Road+Structure Relate
                        </label>
                        <label class="checkbox-inline">
                            <input type="checkbox" value="">C-
                        </label>
                        <label class="checkbox-inline">
                            <input type="checkbox" value="">Option 1
                        </label>
                        <label class="checkbox-inline">
                            <input type="checkbox" value="">Option 2
                        </label>
                        <label class="checkbox-inline">
                            <input type="checkbox" value="">Option 3
                        </label>
                    </form>
                </div>
            </div>
            <div id="listpanel" class="panel-primary">
                <h1>List Panel</h1>
                <div id="file">
                    <table>
                        <th>File Name</th>
                      @foreach (var file in Model)
                {
                    <tr>
                                <td>
                                    <li>
                                 <a href="#" id="fileId">@file.Name</a>
                                    </li>
                                </td>
                            </tr>
                    <br />
                }
                    </table>
                </div>
                @using (Html.BeginForm("Upload", "Document", FormMethod.Post, new {enctype = "multipart/form-data"}))
        {
        <label class="btn btn-block btn-primary">
                Browse &hellip; <input type="file" name="file" id="file" style="display: none;">
                    </label>
            <input type="submit" class="btn" value="Upload">
        }
            </div>

            <div id="frame" class="panel-body">
                <div id="frame">
                    <iframe src="@Url.Action("GetFile", "Document")" width="900px" height="500px"></iframe>
                </div>
            </div>
        </div>
    </body>
    </html>

    <style>
        #h2 {
            background-color: lightblue;
            height: 40px;
        }
#h4 {
    margin-left: 20px;
}
#header {
    margin-left: 50px;
    margin-right: 50px;
}
#frame {
        float: right;
    margin-bottom: 50px;
}
#listpanel {
        float: left;
}
    </style>

    <script>
        $(document).ready(function(e)  {
            // var p = { Data: $('#fileId').val() };
            //var currentDataItem = this.dataItem(this);
            //id = currentDataItem.Id;
            alert($('#fileId').attr('id'));
            var p = { Data: $('#fileId').val() };
            alert(p);
            var id = $('#fileId').text();
            alert(id);
            $('#fileId').click(function () {
                $.ajax(
                {
                    //url: '@Url.Action("GetFile", "Document")?id=' + id,
                    url: '/Document/GetFile',
                    type: "POST",
                    data: {Id:id},
                    success:function(data)
                    {
                    },
                    error:function(e)
                    {
                    }
                });
            })
        });

</script>

3 个答案:

答案 0 :(得分:0)

您的javascript代码应该包含在jQuery加载函数中,如下所示:

 $(function () {

 //Paste all your java script here

 });

这是我在我身边做的唯一改变,而文档控制器中对GetFile的AJAX调用现在正在运行

答案 1 :(得分:0)

正如Denis Wessels所说,你必须在文档就绪块

中包含jquery代码
$( document ).ready(function() {
    var currentDataItem = this.dataItem(this.select());
    id = currentDataItem.Id;
    var p = { Data: $('#fileId').val() };
    $('#fileId').click(function () {
      $.ajax(
      {
          url: '@Url.Action("GetFile", "Document")?id=' + id,
          //url: '/Document/GetFile',
          type: "POST",
         // data: {Id:id},
          success:function(data)
          {
          },
          error:function(e)
          {                    
          }
      });
    })
});

答案 2 :(得分:0)

首先让我纠正你代码中的某些错误。在视图中,没有传递任何可以在action方法中传递的id。因此,要么在FileManager类中将GetData方法的返回类型更改为

Dictionary<int,string>

OR

创建一个模型类说FileManagerModel如下

public class FileManagerModel
{
  public int ID {get;set;}
  public string FileName{get;set;}
}

并将返回类型更改为

List<FileManagerModel>

相应地将视图中的模型更改为

@model Dictionary<int, string> // If the return type is Dictionary<int,string>

然后在视图中更改for循环,如下所示

@foreach(var file in Model)
                    {
                        <tr>
                            <td>
                                <li>
                                    <a href="#" id="fileId" data-id="@file.Key">@file.Value</a>
                                </li>
                            </td>
                        </tr>
                        <br />
                    }

并按以下方式更改您的GetFile方法

public FileStreamResult GetFile(int? id)
        {
            string fileName = "IFrameTest.txt";
            var t = ConfigurationManager.AppSettings["FilePath"];
            string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
            FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
            return File(fs, "text/plain");
        }

在你的方法中添加nullable int arguement,因为在页面加载时你的id将为null。

由于默认情况下该方法是Ajax调用中的HTTPGET方法,因此需要进行如下更改

<script>
    $(document).ready(function(e)  {
        var id = $('#fileId').text();
        $('#fileId').click(function (event) {
            event.preventDefault();
            var id = $(this).data("id");
            $.ajax(
            {
                    url: '@Url.Action("GetFile", "Document")',
                    type: "GET",
                    data: { id: id },
                    success:function(data)
                    {
                    },
                    error:function(e)
                    {
                    }
                });
            })
        });

</script>

在进行这些更改时,它对我有用。我希望这会纠正您的问题

<强>更新

如果您使用IEnumerable,则将数据属性中的Id传递为

<a href="#" id="fileId" data-id="@file.Id ">@file.Name</a>