public class AjaxController : Controller
{
public IActionResult Index()
{
return View();
}
public IConfigurationRoot GetConnection()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appSettings.json").Build();
return builder;
}
public JsonResult Form_Submit()
{
string Result = string.Empty;
MemoryStream stream = new MemoryStream();
Request.Body.CopyTo(stream);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream))
{
string requestBody = reader.ReadToEnd();
if (requestBody.Length > 0)
{
UpdateInsert(JsonConvert.DeserializeObject<Ajax_Model>(requestBody));
}
}
return Json(GetUsers());
}
[NonAction]
private void UpdateInsert(Ajax_Model model)
{
string connectionstring = GetConnection().GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("Insert into Customers(FirstName,Role,Gender) values(@Name,@Role,@Gender)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", model.Name);
cmd.Parameters.AddWithValue("@Role", model.Role);
cmd.Parameters.AddWithValue("@Gender", model.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
private List<Ajax_Model> GetUsers()
{
List<Ajax_Model> model = new List<Ajax_Model>();
string connectionstring = GetConnection().GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("Select * from Customers", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
if (idr.Read())
{
while (idr.Read())
{
model.Add(new Ajax_Model
{
Gender = idr["Gender"].ToString(),
Name = idr["FirstName"].ToString(),
Role = idr["Role"].ToString()
});
}
}
return model;
}
}