如何通过值传递对控制器进行Ajax调用? [英] How to Ajax call to controller with value pass?

查看:41
本文介绍了如何通过值传递对控制器进行Ajax调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i get value from ajax to mvc controller method in 'FileStreamResult' in mvc?I want to pass value from <a href="#" id="fileId">@Model[i].ToString()</a> to controller by 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");
}

FileManager

FileManager

   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>

推荐答案

首先,让我更正您代码中的某些错误.鉴于尚未传递任何可以在action方法中传递的ID.因此,在FileManager类中,将GetData方法的returntype更改为

First all let me correct certain mistakes in your code. In view haven't passed any id that could be passed in the action method. So either in the FileManager class change the returntype of GetData method as

字典< int,string>

创建一个如下模型类,例如FileManagerModel

create a model class say FileManagerModel as follows

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循环

and then in the view change your for loop as follows

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

并按如下所示更改您的GetFile方法

and also change your GetFile method as follows

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");
        }

在您的方法中添加可为null的int争论,因为在页面加载时,您的ID为null.

add nullable int arguement in your method as on page load your id will be null.

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

As the method by default is HTTPGET method in your Ajax call you need to make changes as follows

<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>

进行这些更改后,它对我有用.我希望这可以纠正您的问题

On doing these changes it worked for me .I hope this will rectify your issue

更新

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

If you are using IEnumerable pass the Id in the data attribute as

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

这篇关于如何通过值传递对控制器进行Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆