简体   繁体   English

将选定的下拉字符串值从表中传递给控制器

[英]Passing selected dropdown string value from table in view to controller

I'm working on ASP.NET Core web application where I have a table in my view that displays all requests.我正在开发 ASP.NET Core Web 应用程序,我的视图中有一个表显示所有请求。 each record with drop-down populated with all analysts successfully from my database, So the manager can assign the analyst from drop-down then approve the request.每个带有下拉列表的记录都成功地从我的数据库中填充了所有分析师,因此经理可以从下拉列表中分配分析师,然后批准请求。

My questions:我的问题:

  1. Can I implement this using form for each record instead using JavaScript, I mean using only asp tags?我可以使用每个记录的表单而不是使用 JavaScript 来实现这个,我的意思是只使用 asp 标签吗?

  2. If that should done using JavaScript, Here is my attempt to implement this.如果这应该使用 JavaScript 完成,这是我尝试实现的。 The following code is working only if the Analyst id is integer, but in my case the analyst id is string, so whenever I try to execute this, I got either "null" or "Zero" for the analyst id in the controller.以下代码仅在分析师 id 为整数时才有效,但在我的情况下,分析师 id 是字符串,因此每当我尝试执行此代码时,控制器中的分析师 id 都会得到“空”或“零”。 Here is my ViewModel这是我的 ViewModel

public class RequestViewModel
{
    public IEnumerable<Request> Requests { get; set; }
    public IEnumerable<ApplicationUser> AnalystList { get; set; }
    public Institution Institution { get; set; }
    public string selectedAnalyst { get; set; }
}

Here is my controller这是我的控制器

      public async Task<IActionResult> ApproveRequest(int id, int Analystid)
            {
    
                Request Req = await _db.Request
                    .Include(c => c.Institution)
                    .FirstOrDefaultAsync(c => c.Id == id);
    
                if (Req.Type == SD.TypeRegister)
                {
                    Req.Institution.Status = SD.StatusApproved;
                    Req.Institution.ApprovalDate = DateTime.Now;
                    Req.Institution.Seats = Req.Seats; // new
                    Req.Institution.AnalystId = Analystid.ToString(); //Here I want to get the id as string
    
                }
                else if (Req.Type == SD.TypeSeat)
                {
                    Req.Institution.Seats += Req.Seats;
                }
                else if (Req.Type == SD.TypeSubscription)
                {
                    Req.Institution.Seats = Req.Seats;
                    Req.Institution.Status = SD.StatusApproved;
                    Req.Institution.ApprovalDate = DateTime.Now;
                }
    
                Req.isDone = true;
                await _db.SaveChangesAsync();
                return await CreateApproval(id, SD.StatusApproved);
            }

Here is my View这是我的观点

     @model TestApplication.Models.ViewModels.RequestViewModel
        @using TestApplication.Extensions
        @{
            ViewData["Title"] = "Index";
        }
    
            <div class="tab-pane fade show active" id="Register" role="tabpanel" aria-labelledby="Register-tab">
    
                Registration Requests 
                <div>
                    @if (Model.Requests.Count() > 0)
                    {
                        <table class="table table-striped">
                            <tr class="table-secondary">
                                <th>
                                   Institution Name
                                </th>
                                <th>
                                    Date
                                </th>
                                <th>
                                    Actual seat
                                </th>
                                <th>
                                    Seats
                                </th>
                                <th>
                                   New Seat
                                </th>
                                <th>
                                    Choose Analyst
                                </th>
                                <th>
                                    Accept / Reject
    
                                </th>
                                <th>
                                    Details
                                </th>
                                <th>
                                </th>
                            </tr>
                            @foreach (var item in Model.Requests)
                            {
                                @if (item.Type == "Register" && item.Institution.Status == "Pending") @*need one*@
                                {
                        <tr>
                            <td>
                                @Html.DisplayFor(m => item.Institution.Name)
                            </td>
                            <td>
                                @Html.DisplayFor(m => item.Date)
                            </td>
                            <td>
                                @Html.DisplayFor(m => item.Institution.Seats)
                            </td>
                            <td>
                                @Html.DisplayFor(m => item.ActualSeats)
                            </td>
                            <td>
                                @Html.DisplayFor(m => item.Seats)
                            </td>
                            <td>
                                <select id="selectedAnalyst_@item.Id" asp-for="selectedAnalyst" asp-items=" Model.AnalystList.ToSelectListItem(Model.selectedAnalyst)" class="form-control">
                                       <option selected value="">--- Choose ---</option>
                                </select>
                            </td>
                            <td>
                                  <a class="btn btn-info" asp-controller="Request" asp-action="ApproveRequest" asp-route-id="@item.Id"> accept </a>
                                  <a class="btn btn-info" asp-controller="Request" asp-action="RejectRequest" asp-route-id="@item.Id"> Reject </a>
                            </td>
                            <td>
                                <button type="submit" class="btn btn-success anchorDetail" data-target="#modal-@item.Institution.Id" data-toggle="modal">
                                    View Details
                                </button>
                            </td>
                            <td>
                                <div class="modal fade" id="modal-@item.Institution.Id" tabindex="-1" role="dialog" aria-hidden="true">
                                    <div class="modal-dialog-centered modal-dialog" role="document">
                                        <div class="modal-content">
                                            <div class="modal-header bg-success text-light justify-content-center">
                                                <h5 class="modal-title">Request Details</h5>
                                            </div>
                                            <div class="modal-body justify-content-center" id="MyModalContent">
                                                @await Html.PartialAsync("_RequestDetails", item)
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                                }
                            }
                        </table>
                    }
                    else
                    {
                        <p>No Institutions Exists...</p>
                    }
                </div>
    
    
            </div>
    @section scripts
    {
        <script>
    
            function accept(id) {
                var aid = $('#selectedAnalyst_' + id).val()
                location.href = "/Request/ApproveRequest?id=" + id + "&Analystid=" + aid
            }
    
    
    
            var PostBackURL = '/Request/RequestDetails';
            $(function () {
                $(".anchorDetail").click(function () {
                    var $buttonClicked = $(this);
                    var id = $buttonClicked.attr('data-id');
                    $.ajax({
                        type: "GET",
                        url: PostBackURL,
                        contentType: "application/json; charset=utf-8",
                        data: { "Id": id },
                        cache: false,
                        datatype: "json",
                        success: function (data) {
                            $('#MyModalContent').html(data);
                            $('#myModal').modal('show');
                        },
                        error: function () {
                            alert("Dynamic content load failed.");
                        }
                    });
                })
        </script>
    }
    
    <div class="modal fade" id="MyModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
        <div id='MyModalContent'></div>
    </div>

If you want to pass @item.id and $('#selectedAnalyst_' + id).val() to controller with form,you can do like this.Here is a demo worked(put form outside dropdownlist and button):如果您想将@item.id 和 $('#selectedAnalyst_' + id).val() 传递给带有表单的控制器,您可以这样做。这是一个演示工作(将表单放在下拉列表和按钮之外):

          <form method="post"
                      asp-controller="Request"
                      asp-action="ApproveRequest"
                      asp-route-id="@item.Id">
                    <td>
                        <select id="selectedAnalyst_@item.Id" asp-for="selectedAnalyst" class="form-control">
                            <option selected value="">--- Choose ---</option>
                            <option selected value="1">1</option>
                            <option selected value="2">2</option>
                            <option selected value="3">3</option>

                        </select>
                    </td>
                    <td>

                        <button type="submit">Accept</button>
                    </td>
          </form>

Controller(change Analystid to selectedAnalyst ,so that you can bind asp-for="selectedAnalyst" ,and if you want to get string parameter,you can change it to string selectedAnalyst ):控制器(将Analystid改为selectedAnalyst ,这样就可以绑定asp-for="selectedAnalyst" ,如果要获取字符串参数,可以将其改为string selectedAnalyst ):

public IActionResult ApproveRequest(int id,string selectedAnalyst)
        {
            return Ok();
        }

result:结果: 在此处输入图片说明

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

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