locked
Passing selected dropdown string value from table in view to controller RRS feed

  • Question

  • User1554758465 posted

    I'm working on ASP.NET Core web application where I have a table in my view that displays all requests. 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?

    2. If that should done using JavaScript, Here is my attempt to implement this. 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. Here is my 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>
    Thursday, September 3, 2020 9:14 PM

All replies

  • User1312693872 posted

    Hi,ShahadAlshuhail

    ShahadAlshuhail

    I got either "null" or "Zero" for the analyst id in the controller.

    Using javascript can be easier, I have reproduced your problem, you can try to add  onclick="accept(@item.Id)" to your accept button, Then add event.preventDefault();  to the accept function, it should be work.

    Following is my whole working demo:

    View:

    @model RequestViewModel
    <div>
        <table>
            <tr>
                <th>
                    ID
                </th>
            </tr>
            @foreach (var item in Model.Requests)
            {
        <tr>
            <td>
                <select id="selectedAnalyst_@item.Id" asp-for="selectedAnalyst" class="form-control">
                    <option selected value="0">--- Choose ---</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                </select>
            </td>
            <td>
                <a class="btn btn-info " onclick="accept(@item.Id)" asp-controller="Request" asp-action="ApproveRequest" asp-route-id="@item.Id"> accept </a>
            </td>
            <td>
                <button type="submit" class="btn btn-success anchorDetail" data-id="@item.Id" data-target="#exampleModal" data-toggle="modal">
                    View Details
                </button>
            </td>
            <td>
                <div class="modal fade" id="exampleModal" 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">
    
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
                            </div>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
                
            }
        </table>
    </div>
    
    @section Scripts
    {
        <script>
            function accept(id) {
                event.preventDefault();
                var aid = $('#selectedAnalyst_' + id).val();
                location.href = "/Request/ApproveRequest?id=" + id + "&Analystid=" + aid;
            }
    
            $('.anchorDetail').click(function () {
                event.preventDefault();
                var id = $(this).attr('data-id');
                var aid = $('#selectedAnalyst_' + id).val();
                $.ajax({
                    type: "Post",
                    url: "/Request/RequestDetails",
                    data: {
                        "id": id,
                        "Analystid":aid
                    },
                    success: function (data) {
                        $("#MyModalContent").html(data);
                        $('#exampleModal').modal();
                    }
                })
            });
        </script>
    
    }
    
    <div class="modal fade" id="MyModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
        <div id='MyModalContent'></div>
    </div>

    Controller:

    public IActionResult Index()
            {
                RequestViewModel requestViewModel = new RequestViewModel
                {
                    Requests = new List<Request>
                   {
                      new Request { Id = "1" },
                      new Request { Id = "2" },
                      new Request { Id = "3" }
                   },
                };
                return View(requestViewModel);
            }
    
            public async Task<IActionResult> ApproveRequest(int id, int Analystid)
            {
    
                return Ok("id:" + id + "|" + "Analystid:" + Analystid);
            }
    
            public IActionResult RequestDetails(int id, int Analystid)
            {
    
                return Ok("id:" + id + "|" + "Analystid:" + Analystid);
            }

    Model:

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

    Result:

    Best Regards,

    Jerry Cai

    Friday, September 4, 2020 7:58 AM