【问题标题】:How to pass a value from foreach loop in the view to the controller in ASP.NET Core MVC?如何将视图中 foreach 循环中的值传递给 ASP.NET Core MVC 中的控制器?
【发布时间】:2021-12-12 18:12:04
【问题描述】:

我的视图中有一个表,它的行由 foreach 循环填充。该表的一部分如下:

@foreach (var item in Model.PmModel)
{
   <td>@Html.DisplayName(item.pmNumber.ToString())</td>
   <td>
        <button type="button" class="btn btn-info btn-table btn-modal">Upload</button>
   </td>
}

我在每一行都有一个按钮,通过按下每个按钮,会出现一个模式表单来上传文件。我使用以下代码上传文件并根据文件信息填充数据库列。但我需要将 pmId 从视图中移至以下操作:

public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file != null)
            {
                if (file.Length > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var fileExtension = Path.GetExtension(fileName);
                    var newFileName = string.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);
                    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/PmFiles/UploadedByUsers", newFileName);
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    var fileElements = new Models.FileRepository()
                    {
                        fileId = 0,
                        fileName = newFileName,
                        isDownloaded = false,
                        pm = _pmRepository.GetPmById(int Id), //I need to get Id from view
                        uploadDate = DateTime.Now,
                    };
                    _fileRepository.InsertFile(fileElements);
                    _fileRepository.SaveChanges();
                }
            }
            return RedirectToAction("PmPage");
        } 

我使用 Bootstrap 模态:

@section Modal{
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"
     dir="ltr">
    <div class="modal-dialog">
        <form method="post" enctype="multipart/form-data" asp-controller="Page" asp-action="UploadFile">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">File Upload</h5>
                    <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row mt-2" dir="rtl">
                        <label class="form-label" for="customFile">Select your file:</label>
                        <input type="file" name="file" class="form-control" id="customFile" />
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-mdb-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Upload</button>
                </div>
            </div>
        </form>
    </div>
</div>

}

在视图中,我可以使用item.pmNumber 找到 pmId,但我不知道如何将它的值用于我的控制器。请帮帮我。

更新:此脚本通过按下按钮触发模式。

<script type="text/javascript">
    $(document).ready(function () {
        $('.btn-modal').click(function () {
            $('#exampleModal').modal('show');
        });
    });
</script>

【问题讨论】:

  • 您可以将视图中的 id 作为发布请求的一部分传递并获取它public async Task&lt;IActionResult&gt; UploadFile(IFormFile file, int Id) 您还可以创建将IFormFileId 包装为属性的类a。跨度>
  • 您必须在调用上传操作的位置显示您的 javascript 和模式视图
  • @Serge 我更新了问题
  • 谢谢,您打开此模式的代码在哪里?
  • @Serge 我更正了主要问题中的按钮类。请看一看。我用过 MDBootstrap

标签: asp.net-core-mvc


【解决方案1】:

您可以在模态中添加隐藏输入,并将模态主体放在 foreach 部分中,以将 item.pmNumber 传递给隐藏输入。

这是一个您可以关注的工作演示:

型号:

public class FileModel
{
    public List<PmModel> PmModel { get; set; }
}
public class PmModel
{
    public int pmNumber { get; set; }
}

查看:

@model FileModel
@{ 
    int i = 0;   //add this....
}
@foreach (var item in Model.PmModel)
{
    <td>@Html.DisplayName(item.pmNumber.ToString())</td>
    <td>                                            //change here....
        <button type="button"  data-toggle="modal" data-target="#exampleModal_@i" class="btn btn-info btn-table btn-modal">Upload</button>
    </td>                       //change here.....
    <div class="modal fade" id="exampleModal_@i" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"
         dir="ltr">
        <div class="modal-dialog">
            <form method="post" enctype="multipart/form-data" asp-controller="Page" asp-action="UploadFile">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">File Upload</h5>
                        <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row mt-2" dir="rtl">
                              <!--add this-->
                            <input hidden name="id" value="@item.pmNumber" />  
                        </div>
                        <div class="row mt-2" dir="rtl">
                            <label class="form-label" for="customFile">Select your file:</label>
                            <input type="file" name="file" class="form-control" id="customFile" />
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-mdb-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Upload</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    i++;            //add here.........
}


@section Scripts {
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <!-- Google Fonts -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
    <!-- Bootstrap core CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- Material Design Bootstrap -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet">
    <!-- JQuery -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Bootstrap tooltips -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <!-- MDB core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js"></script>
}

控制器:

public class PageController : Controller
{
    public async Task<IActionResult> UploadFile(IFormFile file,int id)
    {
        //do your stuff...
        return View();
    }
}

此外,您还可以为 modal 创建一个局部视图(此局部视图仍然需要隐藏输入)以避免循环模态正文代码。参考this answer

【讨论】:

  • 我尝试使用此解决方案,但没有成功。您忘记提及与模态相关的脚本部分。我认为正文底部的模态脚本是在循环之前加载的。所以我们无法匹配 ID
  • 嗨@Fardin,对于这个解决方案,不需要使用任何jquery来传递id。它可以从 foreach 循环中获取 id。请以任何方式分享您的代码。
  • 嗨@Fardin,您可以看到我将模态代码放入foreach循环,并在模态代码中添加隐藏输入并使用value="@item.pmNumber"设置值。每次我触发模态时,它都会显示具有不同 ID 的模态。并且表单提交会动态发布id和文件。
  • 请检查主要问题中的更新。我们需要为每一行更改#exampleModal。所以,#exampleModal_@i 不匹配。
  • 嗨@Fardin,实际上我认为您可能没有仔细阅读我的答案。你看到我把模态放在循环里面了吗?对于模态弹出窗口,您可以将data-toggle="modal" data-target="#exampleModal_@i" 添加到按钮以自动使其工作而不是使用jquery。这是默认的引导模式用法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-30
  • 2020-10-24
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多