ASP. NET Проблема Core OnPost () с загрузкой данных - PullRequest
1 голос
/ 10 июля 2020

Я пытаюсь передать IEnumerable моему методу OnPost(), но все, что я пробовал до сих пор, просто приводит к тому, что он равен нулю или имеет Count 0. В OnGet() я бросаю все необходимые данные в нем, и я могу легко распечатать его на веб-странице. Вот код, который у меня есть:

EditLocations.cs html:

@page "{assessmentId}"
@model CustomerPageTest.Pages.View.EditLocationsModel
@{
    ViewData["Title"] = "EditLocations";
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<div class="col-md-offset-4 justify-content-center">
    <h1 style="color:yellowgreen">Edit Locations</h1>
</div>
<br /><br />

      <form method="post">
          <div class="form-group">
              <input type="submit" value="Submit" class="btn btn-dark text-light" />
          </div>
      </form>

      
<br />
<form method="get">
    <div class="form-group">
        <div class="input-group">
            <input type="search" placeholder="Search ID, Host, Datacenter, Cluster, Location Name, City, State, or Bandwidth" class="form-control" asp-for="SearchTerm" />
        </div>
    </div>
</form>

<form method="post">
    <table class="table">
        <tr class="text-light" style="border-top: hidden !important">
            <td>ID</td>
            <td>Host</td>
            <td>Datacenter</td>
            <td>Cluster</td>
            <td>Location Name</td>
            <td>City</td>
            <td>State</td>
            <td>Bandwidth</td>
        </tr>
        @foreach (var location in Model.LocationViews)
        {
            <tr>
                <td><input type="checkbox" id="@location.isChecked" name="@location.isChecked" /></td>
                <td class="text text-light">
                    @location.vHost_id
                    <input type="hidden" id="@location.vHost_id" name="@location.vHost_id" />
                </td>
                <td class="text text-light">
                    @location.Host
                    <input type="hidden" id="@location.Host" name="@location.Host" />
                </td>
                <td class="text text-light">
                    @location.Datacenter
                    <input type="hidden" id="@location.Datacenter" name="@location.Datacenter" />
                </td>
                <td class="text text-light">
                    @location.Cluster
                    <input type="hidden" id="@location.Cluster" name="@location.Cluster" />
                </td>
                <td class="text text-light">
                    @location.name
                    <input type="hidden" id="@location.name" name="@location.name" />
                </td>
                <td class="text text-light">
                    @location.city
                    <input type="hidden" id="@location.city" name="@location.city" />
                </td>
                <td class="text text-light">
                    @location.state
                    <input type="hidden" id="@location.state" name="@location.state" />
                </td>
                <td class="text text-light">
                    @location.bandwidth
                    <input type="hidden" id="@location.bandwidth" name="@location.bandwidth" />
                </td>
                <td>
                    <!--<a class="btn btn-dark"
                    asp-page="/View/EditAssessment" asp-route-assessmentId="">
                        <i class="glyphicon glyphicon-pencil"></i>
                    </a>-->
                </td>
            </tr>
        }
    </table>
</form>

EditLocations.cs html .cs:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using KelderModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace CustomerPageTest.Pages.View
{
    public class EditLocationsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public string SearchTerm { get; set; } //Search term for search bar

        [BindProperty(SupportsGet = true)]
        public IEnumerable<LocationView> LocationViews { get; set; }

        public int assessment_id { get; set; }

        public void OnGet(int assessmentId)
        {
            assessment_id = assessmentId;
            LocationViews = GetLocationViewsByAssessment(assessmentId);
            bool intOrString = false; //If false, its a string, if true, its an int
            try
            {
                int convertToInt = Int32.Parse(SearchTerm);
                intOrString = true;
            }
            catch (Exception) { }

            if (intOrString)
            { //Whole if statement is for the search bar, enables searching data in any column
                if (!IsNullOrEmpty(GetLocationById(Convert.ToInt32(SearchTerm))))
                    LocationViews = GetLocationById(Convert.ToInt32(SearchTerm));
                else if (!IsNullOrEmpty(GetLocationByBandwidth(Convert.ToInt32(SearchTerm))))
                    LocationViews = GetLocationByBandwidth(Convert.ToInt32(SearchTerm));
            }
            else
            {
                if (!IsNullOrEmpty(SearchLocationByHost(SearchTerm)))
                    LocationViews = SearchLocationByHost(SearchTerm);
                else if (!IsNullOrEmpty(SearchLocationByDatacenter(SearchTerm)))
                    LocationViews = SearchLocationByDatacenter(SearchTerm);
                else if (!IsNullOrEmpty(SearchLocationByCluster(SearchTerm)))
                    LocationViews = SearchLocationByCluster(SearchTerm);
                else if (!IsNullOrEmpty(SearchLocationByLocationName(SearchTerm)))
                    LocationViews = SearchLocationByLocationName(SearchTerm);
                else if (!IsNullOrEmpty(SearchLocationByCity(SearchTerm)))
                    LocationViews = SearchLocationByCity(SearchTerm);
                else if (!IsNullOrEmpty(SearchLocationByState(SearchTerm)))
                    LocationViews = SearchLocationByState(SearchTerm);
            }
        }

        public void OnPost()
        {
            foreach(var location in LocationViews)
            {
                location.isChecked = true;
            }
        }

        public IEnumerable<LocationView> GetLocationViewsByAssessment(int assessmentID) //Creates a list of locations based off of the locations in the database and assessment_id given
        {
            List<LocationView> returnList = new List<LocationView>();
            using (var context = new DataWarehouseContext())
            {
                List<int> vHostIDs = context.RvtoolsVHost //Gets list of vHostIDs mainly as a counter for the rows corresponding to the assessment_id
                    .Where(a => a.AssessmentId == assessment_id)
                    .Select(b => b.VHostId)
                    .ToList();

                foreach(int host in vHostIDs)
                {
                    LocationView temp = new LocationView();
                    temp.isChecked = false;
                    temp.assessment_id = assessmentID;
                    temp.vHost_id = host;

                    temp.location_id = context.Location //Returns LocationID from Location database table
                        .Where(a => a.VHostId == host)
                        .Select(b => b.LocationId)
                        .SingleOrDefault();

                    temp.name = context.Location //Returns Location Name from Location database table
                        .Where(a => a.VHostId == host)
                        .Select(b => b.Name)
                        .SingleOrDefault();

                    temp.city = context.Location //Returns City from Location database table
                        .Where(a => a.VHostId == host)
                        .Select(b => b.City)
                        .SingleOrDefault();

                    temp.state = context.Location //Returns State from Location database table
                        .Where(a => a.VHostId == host)
                        .Select(b => b.State)
                        .SingleOrDefault();

                    temp.bandwidth = context.Location //Returns City from Location database table
                        .Where(a => a.VHostId == host)
                        .Select(b => b.Bandwidth)
                        .SingleOrDefault();

                    temp.Host = context.RvtoolsVHost //returns Host Name from Host table using the vHostID that points at it
                        .Where(a => a.VHostId == host)
                        .Select(b => b.Name)
                        .FirstOrDefault();

                    temp.Datacenter = context.RvtoolsVHost //returns Cluster Name from Cluster table using the vHostID that points at it
                        .Where(a => a.VHostId == host)
                        .Select(b => b.Datacenter.Name)
                        .FirstOrDefault();

                    temp.Cluster = context.RvtoolsVHost //returns Cluster Name from Cluster table using the vHostID that points at it
                        .Where(a => a.VHostId == host)
                        .Select(b => b.VCluster.Name)
                        .FirstOrDefault();

                    returnList.Add(temp);
                }
            }
            return returnList;
        }

        public IEnumerable<LocationView> GetLocationById(int id) //Should only return a single location since ID is specific
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(id.ToString()) || c.location_id.ToString().Equals(id.ToString())
                   orderby c.bandwidth
                   select c;
        }

        public IEnumerable<LocationView> GetLocationByBandwidth(int id) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(id.ToString()) || c.bandwidth.ToString().StartsWith(id.ToString())
                   orderby c.bandwidth
                   select c;
        }

        public IEnumerable<LocationView> SearchLocationByHost(string name = null) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(name) || c.Host.StartsWith(name)
                   orderby c.Host
                   select c;
        }

        public IEnumerable<LocationView> SearchLocationByDatacenter(string name = null) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(name) || c.Datacenter.StartsWith(name)
                   orderby c.Datacenter
                   select c;
        }

        public IEnumerable<LocationView> SearchLocationByCluster(string name = null) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(name) || c.Cluster.StartsWith(name)
                   orderby c.Cluster
                   select c;
        }

        public IEnumerable<LocationView> SearchLocationByLocationName(string name = null) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(name) || c.name.StartsWith(name)
                   orderby c.name
                   select c;
        }

        public IEnumerable<LocationView> SearchLocationByCity(string name = null) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(name) || c.city.StartsWith(name)
                   orderby c.city
                   select c;
        }

        public IEnumerable<LocationView> SearchLocationByState(string name = null) //Can return many locations
        {
            return from c in LocationViews
                   where string.IsNullOrEmpty(name) || c.state.StartsWith(name)
                   orderby c.state
                   select c;
        }



        public bool IsNullOrEmpty<LocationView>(IEnumerable<LocationView> enumerable)
        {
            return enumerable == null || !enumerable.Any();
        }

    }
}

Любые мысли будем очень признательны!

Ответы [ 2 ]

0 голосов
/ 11 июля 2020

Во-первых, я обнаружил в вашей форме, что кнопка отправки и таблица не в той же форме, поэтому при нажатии кнопки данные таблицы не будут переданы. И тогда привязка модели неверна, вы можете использовать name="LocationViews[@i].xxx" для привязки данных. Вот демонстрация работы: cs html:

<div class="col-md-offset-4 justify-content-center">
    <h1 style="color:yellowgreen">Edit Locations</h1>
</div>
<br />
<br />



<br />


<form method="post">
    <table class="table">
        <tr class="text-light" style="border-top: hidden !important">
            <td>ID</td>
            <td>Host</td>
            <td>Datacenter</td>
            <td>Cluster</td>
            <td>Location Name</td>
            <td>City</td>
            <td>State</td>
            <td>Bandwidth</td>
        </tr>
        @for (int i = 0; i < Model.LocationViews.Count(); i++) 
        {
            <tr>
                <td><input type="checkbox" asp-for="LocationViews.ElementAt(i).isChecked" name="LocationViews[@i].isChecked" /></td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).vHost_id
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).vHost_id" name="LocationViews[@i].vHost_id" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).Host
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).Host" name="LocationViews[@i].Host" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).Datacenter
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).Datacenter" name="LocationViews[@i].Datacenter" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).Cluster
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).Cluster" name="LocationViews[@i].Cluster" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).name
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).name" name="LocationViews[@i].name" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).city
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).city" name="LocationViews[@i].city" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).state
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).state" name="LocationViews[@i].state" />
                </td>
                <td class="text text-light">
                    @Model.LocationViews.ElementAt(i).bandwidth
                    <input type="hidden" asp-for="LocationViews.ElementAt(i).bandwidth" name="LocationViews[@i].bandwidth" />
                </td>
                <td>
                    <!--<a class="btn btn-dark"
                    asp-page="/View/EditAssessment" asp-route-assessmentId="">
                        <i class="glyphicon glyphicon-pencil"></i>
                    </a>-->
                </td>
            </tr>
        }
    </table>
    <input type="submit" value="Submit" class="btn btn-dark text-light" />
</form>

cs html .cs:

public class EditLocationsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public IEnumerable<LocationView> LocationViews { get; set; }
        public ActionResult OnGet()
        {
            List < LocationView > list = new List<LocationView>();
            LocationView l1 = new LocationView { isChecked = false, vHost_id = 1, city = "city1", Host = "h1", Cluster = "c1", Datacenter = "d1", name = "location1", state = "state1", bandwidth = "b1" };
            LocationView l2 = new LocationView { isChecked = true, vHost_id = 2, city = "city2", Host = "h2", Cluster = "c2", Datacenter = "d2", name = "location2", state = "state2", bandwidth = "b2" };
            list.Add(l1);
            list.Add(l2);
            LocationViews = list;
            return Page();

        }
        public void OnPost() {
          
        }
    }

Результат : введите описание изображения здесь

0 голосов
/ 10 июля 2020

var lvs = from ld in context.Location
        join h in context.HostTable on h.hostId equals ld.VHostId
        join c in context.ClusterTable on c.hostId equals ld.VHostId
        
        where vHostIDs.Contains(ld.VHostId)
        select new LocationView {
            isChecked = false,
            assessment_id = assessmentID,
            location_id = ld.LocationId,
            name = ld.Name,
            city = ld.City,
            state = ld.State,
            bandwidth = ld.Bandwidth,
            host = h.Name,
            Datacenter = c.Datacenter.Name,
            Cluster = c.VCluster.Name
            
        }

Вместо l oop используйте Linq

...