Reputation: 123
I am trying to read the list of state from the db table into @html.dropdownlistfor in the data entry form that I am writing.
I am using SqlClient
in my controller to achieve this. Below is the code for controller and view page.
[HttpGet]
public ActionResult DataEntry()
{
var query = "SELECT State, Description FROM dbo.CountryState WHERE Country = 'USA'";
//I declared the connection string in the beginning of the controller as below
//string cnn = "Server=mydb;Database=db_registry_data;Trusted_Connection=True;";
List<DataForm> stateList = new List<DataForm>();
using (SqlConnection con = new SqlConnection(cnn))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataForm dataForm = new DataForm();
dataForm.Description = Convert.ToString(reader["Description"]); // description: full name of state
dataForm.State = Convert.ToString(reader["State"]); //state: initials of the state
stateList.Add(dataForm);
}
}
con.Close();
}
ViewBag.States = stateList;
return View();
}
Here is my view page
@model DataEntry.Models.DataForm
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("DataEntry", "DataForm", new { @class = "form-control", style = "display: flex;" }))
{
@Html.AntiForgeryToken()
<div class="form-group col-md-6">
<label for="inputEmail4">State: </label>
@Html.DropDownListFor(m => m.State, new SelectList(ViewBag.States, "State","Description"), "--Please Select--", new { @class = "form-control"})
</div>
}
Finally, I am getting the following error when I try to run the project.
Microsoft.Data.SqlClient.SqlException: 'A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The target principal name is incorrect.)'
Win32Exception: The target principal name is incorrect.
I would love sone help to fix this error. Thank you!
P.S. I didn't post the [HttpPost]
one of the function since it pulls the form successfully before adding @Html.DropDownListFor(m => m.State, new SelectList(ViewBag.States, "State","Description"), "--Please Select--", new { @class = "form-control"})
part in the view page.
Upvotes: 0
Views: 8493
Reputation: 1
Try to add:
TrustServercertificate=true
to your connection string.
Upvotes: 0
Reputation: 123
I added Encrypt=False;
at the end of the connection string and it worked like a charm. Thanks everyone for your time to help me.
Upvotes: 1