Заполните раскрывающийся список на основе тегов местоположения

Я пытался сделать это как редактирование, но он был отклонен; Я не понимаю, почему.

Вышеупомянутое выдает исключение, если вы вызываете его с помощью Enum, в котором есть сочетание пользовательских атрибутов и простых элементов, например

public enum CommentType
{
    All = 1,
    Rent = 2,
    Insurance = 3,
    [Display(Name="Service Charge")]
    ServiceCharge = 4
}

So Я немного изменил код, чтобы проверить пользовательские атрибуты, прежде чем пытаться получить к ним доступ, и использовать имя, если ни один не найден.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static class EnumHelper<T>
{
    public static IList<T> GetValues(Enum value)
    {
        var enumValues = new List<T>();

        foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
        }
        return enumValues;
    }

    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }

    public static IList<string> GetNames(Enum value)
    {
        return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
    }

    public static IList<string> GetDisplayValues(Enum value)
    {
        return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
    }

    private static string lookupResource(Type resourceManagerProvider, string resourceKey)
    {
        foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
        {
            if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
            {
                System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
                return resourceManager.GetString(resourceKey);
            }
        }

        return resourceKey; // Fallback with the key name
    }

    public static string GetDisplayValue(T value)
    {
        var fieldInfo = value.GetType().GetField(value.ToString());

        var descriptionAttributes = fieldInfo.GetCustomAttributes(
            typeof(DisplayAttribute), false) as DisplayAttribute[];

        if (descriptionAttributes.Any() && descriptionAttributes[0].ResourceType != null)
            return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);

        if (descriptionAttributes == null) return string.Empty;
        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
    }
}
1
задан Mohammed Ismail 16 January 2019 в 11:42
поделиться

1 ответ

Вы можете структурировать свою функцию поиска в отдельном файле PHP, чтобы иметь чистый маршрут URL. Обратите внимание, что этот запрос будет подвержен SQL-инъекциям. Это всего лишь общий пример

, например

//  search.php
//  GET request
    function SearchLocations() {
        $conn = new mysqli('localhost', 'root', '', 'tutors') or die ('Cannot connect to db');
        $result = $conn->query("select id,name,Location_tags from tutor_location where Location_tags='%". 

Вы можете структурировать свою функцию поиска в отдельном файле PHP, чтобы иметь чистый маршрут URL. Обратите внимание, что этот запрос будет подвержен SQL-инъекциям. Это всего лишь общий пример

, например

[110]

HTML:

<input type="text" name="location_input" id="location_input">
<select name="locations" id="locations">

Тогда в вашем коде JavaScript:

 $("#location_input").keydown(function(){
            const location = $("#location_input").val();
            $("#locations").hmlt(''); //reset dropdown
            // do ajax call to get locations
            $.ajax({
                url: 'search.php',  //replace this with your route of the search function
                data: {location}, //pass location as body data
                dataType: 'json' //expect a json response back
                success: function(data) {
                    data.forEach(function(el) { //loop over the json response
                        let option = `<option id=${el.id} value=${el.name}>${el.name}</option>`
                        $("#locations").append(option); //append locations to select dropdown
                    });
                },
                error: function(err) {  //error functions
                    console.log(err);
                    alert("Error")
                }
            });
        });
GET['location']."%'"); $locations = []; while ($row = $result->fetch_assoc()) { $locations[] = $row; } return json_encode($locations); }

HTML:

<input type="text" name="location_input" id="location_input">
<select name="locations" id="locations">

Тогда в вашем коде JavaScript:

 $("#location_input").keydown(function(){
            const location = $("#location_input").val();
            $("#locations").hmlt(''); //reset dropdown
            // do ajax call to get locations
            $.ajax({
                url: 'search.php',  //replace this with your route of the search function
                data: {location}, //pass location as body data
                dataType: 'json' //expect a json response back
                success: function(data) {
                    data.forEach(function(el) { //loop over the json response
                        let option = `<option id=${el.id} value=${el.name}>${el.name}</option>`
                        $("#locations").append(option); //append locations to select dropdown
                    });
                },
                error: function(err) {  //error functions
                    console.log(err);
                    alert("Error")
                }
            });
        });
0
ответ дан Adis 16 January 2019 в 11:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: