Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • OddConcept 2 posts 22 karma points
    Jun 29, 2015 @ 21:08
    OddConcept
    0

    Surface Controller With Grid

    I am new to MVC and this is my first attempt at creating a SurfaceController. It is a basic form with 2 dropdowns. Origin Port and Destination port. When the user selects an origin port then there is an ajax call that gets available destination ports.... All this is working until here.

    When I submit the form I need to go to the Database and get all Records with the Origin Port and Destination Port that were selected. When I get to the HttpPost call "RateRequest" how do I send the values back to the cshtml page. The "GetAllFreightRates" call has records but the WebGrid does not bind with the new values.

    I would greatly appreciate a kick in the right direction...

    This is my surface Controller:

    public class RateRequestSurfaceController: SurfaceController
        {
            [HttpPost]
            public ActionResult RateRequest(RateRequestModel model)
            {
               ////***** At this point only model.OiginPort and model.DestinationPorts have value.
    
                if (ModelState.IsValid)
                {
                    model.FreightRates = FreightRateServices.GetAllFreightRates();
                }
                return CurrentUmbracoPage();
            }
    
    
            [HttpPost]
            public ActionResult BindDischargePorts(string originPortId)
            {
                try
                {
                    var data = PortServices.GetAvailableDischargePorts(string.IsNullOrEmpty(originPortId) ? (int?)null : Convert.ToInt32(originPortId)).ToList();
                    data.Insert(0, new PortModel() { Name = "-- All --", Id = 0 });
                    return Json(new { ok = true, data, message = string.Empty });
                }
                catch (Exception ex)
                {
                    return Json(new { ok = false, message = ex.Message });
                }
            }
    
            [ChildActionOnly]
            public ActionResult RenderActionResult()
            {
                var rateRequestmodel = new RateRequestModel
                {
                    OriginPorts = PortServices.GetAvailableLoadingPorts().AsEnumerable().Select(x => new SelectListItem
                        {
                            Text = x.Name,
                            Value = x.Id.ToString()
                        }).ToList(),   
                    DestinationPorts = PortServices.GetAvailableDischargePorts().AsEnumerable().Select(x => new SelectListItem
                        {
                            Text = x.Name,
                            Value = x.Id.ToString()
                        }).ToList(),
                    FreightRates = Enumerable.Empty<FreightRateModel>()
                };
    
                return PartialView("RateRequest", rateRequestmodel);
            }
    
    
        }
    

    My Model:

    public class RateRequestModel {

    [DisplayName("Origin Port")]
    public IEnumerable<SelectListItem> OriginPorts { get; set; }
    public int OriginPortId { get; set; }
    
    [DisplayName("Destination Port")]
    public IEnumerable<SelectListItem> DestinationPorts { get; set; }
    public int DestinationPortId { get; set; }
    
    public IEnumerable<FreightRateModel> FreightRates { get; set; } 
    

    }

    cshtml:

    @using (Html.BeginUmbracoForm("RateRequest", "RateRequestSurface", Model, new { @class = "rateRequestForm" }))
    {
        @Html.ValidationSummary(true)
    
        <div>
            @Html.ValidationSummary()
        </div>
    
        <div>
            @Html.LabelFor(x=> x.OriginPorts):
            @Html.DropDownListFor(x => x.OriginPortId, Model.OriginPorts, "-- All --")
        </div>
        <div>
            @Html.LabelFor(x => x.DestinationPorts):
            @Html.DropDownListFor(x => x.DestinationPortId, Model.DestinationPorts, "-- All --")
        </div>
    
        <input type="submit" value="Search Rate Request" class="jbutton" />
    
    
        <div id="divFreightRates" class="innerContentContainer ui-helper-padding">
    
            <div class="row-fluid">
                @{
                    //var grid = new WebGrid(FreightRateServices.GetAllFreightRates());
                    var grid = new WebGrid(Model.FreightRates, rowsPerPage: 25, ajaxUpdateContainerId: "divFreightRates", defaultSort: "OriginPort");
                    //grid.Bind(Model.FreightRates, rowCount: Model.FreightRates.Count(), autoSortAndPage: false);
                    grid.Pager(WebGridPagerModes.All);
    
                }
                <div>
                    @grid.GetHtml(
                        tableStyle: "gvThemeBlue gvResults"
                        )
                </div>
            </div>
        </div>
    
        <script type="text/javascript">
    
            $(function () {
                var gvResults = $('.gvResults');
                if (gvResults != null && gvResults.children('thead').length > 0) {
                    //var hCol1 = gvResults.find('tr th').filter(function () { return $(this).text() === "Id"; }).index();
                    gvResults.dataTable({
                        "bJQueryUI": true,
                        "bPaginate": true,
                        "iDisplayLength": 50,
                        "sPaginationType": "full_numbers",
                        "bLengthChange": false,
                        "bInfo": false,
                        "bFilter": true,
                        "bAutoWidth": false,
                        "sDom": '<"H"Tfr>t<"F"ip>',
                        "aaSorting": [],
                        //"aoColumnDefs": [{ "bVisible": false, "aTargets": [hCol1] }, { 'bSortable': false, 'aTargets': [0] }],
                        "fnRowCallback": function (nRow) {
                            return nRow;
                        }
                    });
                }
            });
    
            $('#OriginPortId').on('change', function () {
    
                var selectedValue = $("#OriginPortId option:selected").val();
                var destinationPortDropdown = $("#DestinationPortId");
                $.post('@Url.Action("BindDischargePorts", "RateRequestSurface")', { originPortId: selectedValue }, function (data) {
                    if (data.ok) {
                        destinationPortDropdown.empty();
                        $.each(data.data, function (index, itemData) {
                            destinationPortDropdown.append($('<option></option>').val(itemData.Id).html(itemData.Name));
                        });
    
                    } else {
                        alert('Error Loading Data.');
                    }
                });
            });
    
        </script>
    
    
    
    }
    
  • OddConcept 2 posts 22 karma points
    Jun 30, 2015 @ 20:26
    OddConcept
    0

    I ended up passing the data in the ViewData, because I could not figure out how to pass the data back using the Model.

    [HttpPost]
    public ActionResult RateRequest(RateRequestModel model)
    {
        if (ModelState.IsValid)
        {
            BindDropDowns();
            ViewData["FreightRates"] = TestClass.GetInfo(model.OriginPortId, model.DestinationPortId);
        }
        return CurrentUmbracoPage();
    }
    
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies