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 });
}
}