Stpete111
Stpete111

Reputation: 3437

ASP.NET web app with Javascript - properly populate database columns

Creating a CRUD app in ASP.NET with C#, Javascript and SQL Server 2017.

The database table has three columns, Country, CountryCode and CountryCodeId that I'm attempting to populate with a create function (yes I'm aware of the relational design flaw here - that's outside of the scope of the question)...

I have an enum class that looks like this:

 public enum Country
    {
        [Description("Afghanistan")] AFG = 1,
        [Description("Åland Islands")] ALA = 2,
        [Description("Albania")] ALB = 3,
    }

I have a dropdown menu in the UI which displays the names of the country as shown in the Description piece above. Let's say the chosen value of the dropdown is Afghanistan. What I need to do upon execution of the create function is populate the Country column of the database with Afghanistan, the CountryCodecolumn with AFG and the CountryCodeId column with 1.

My Javascript skills are what are the most lacking, and I can only get the CountryCodeId to work, out of the three. This is my JS code - the question marks are where I'm lost:

  async function newRecord(form) {
        var record = {};
        record.countryCodeId = $('#country').val();
        record.countryCode = $("???").val();
        record.country = $("???").val();
        var response = await fetch(`${endpoint}api/record`, {
            method: 'POST',
            crossDomain: true,
            cache: 'no-cache',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(record)
        });

EDIT 1: as requested, here is the C# Insertfunction:

public bool Insert(Record record)
        {
            SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("Production"));
            connection.Open();
            using (connection)
            {
                string query = "INSERT INTO [dbo].[Table]" +
                  "([Country]" +
                  ",[CountryCode]" +
                  ",[CountryCodeId]")
                  "VALUES " +
                  "(@Country" +
                  ",@CountryCode" +
                  ",@CountryCodeId")";
                return connection.Execute(query, record) > 0;
            }
        }

EDIT 2:

Controller action method for Insert:

[HttpPost]
public JsonResult Insert(Record record)
{
    try
    {
        bool result = _repository.Insert(record);
        return new JsonResult(new OperationResult { Success = true });
    }
    catch (Exception ex)
    {
        return new JsonResult(new OperationResult { Success = false, Error = ex.Message });
    }
}

Upvotes: 2

Views: 121

Answers (1)

sh1rts
sh1rts

Reputation: 1884

Try this: -

using System.ComponentModel;
.
.
void ProcessCountry(string countryCode)
{
    Country country;

    // i.e. countryCode = "AFG"
    if (Enum.TryParse(countryCode, out country))
    {
        string description = null; 

        try
        {
            FieldInfo fieldInfo = country.GetType().GetField(country.ToString());
            DescriptionAttribute[] attributes = 
               (DescriptionAttribute[])
                   fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

            description = ((attributes.Length != 0) ? 
                                attributes[0].Description : 
                                country.ToString());
        }
        catch (System.NullReferenceException)
        {
        }
        finally
        {
            if (string.IsNullOrEmpty(description))
            {
                description = "Unknown";
            }
        }

        int value = Convert.ToInt32(country);
        Console.Write($"countryCode: {countryCode}, description: {description}, value: {value}");
    }
}

The FieldInfo/DescriptionAttribute stuff pulls the description out of the System.ComponentModel.Description attribute, and as you've given your enum values INT values then you can parse them as Int.

Upvotes: 1

Related Questions