繁体   English   中英

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

[英]How to Ajax call to controller with value pass?

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

调节器

      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>

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

 $(function () {

 //Paste all your java script here

 });

这是我在我身边做出的唯一改变,现在Document控制器中对GetFile的AJAX调用正在进行中

正如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)
          {                    
          }
      });
    })
});

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

Dictionary<int,string>

要么

创建一个模型类说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>

在做这些改变时,它对我有用。我希望这会纠正你的问题

UPDATE

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM