Hi moepyag,
Refer below example.
Database
CREATE TABLE Students
(
StudentID INT IDENTITY PRIMARY KEY,
Name VARCHAR(10)
)
CREATE TABLE StudentsDetails
(
ID INT IDENTITY PRIMARY KEY,
Age INT,
Address VARCHAR(100),
StudentID INT,
CONSTRAINT FK_Students FOREIGN KEY(StudentID) REFERENCES Students(StudentID)
)
Model
public class StudentModel
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Code
public class HomeController : Controller
{
private IConfiguration Configuration;
public HomeController(IConfiguration _configuration)
{
this.Configuration = _configuration;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(StudentModel model)
{
int studentId;
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
string sql = "INSERT INTO Students (Name) VALUES (@Name) SELECT SCOPE_IDENTITY()";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Name", model.Name);
con.Open();
studentId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
sql = "INSERT INTO StudentsDetails (Age, Address, StudentID) VALUES (@Age, @Address, @StudentID)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Age", model.Age);
cmd.Parameters.AddWithValue("@Address", model.Address);
cmd.Parameters.AddWithValue("@StudentID", studentId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
return View();
}
}
HTML
@model Sample_207462.Models.StudentModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<table cellpadding="0" cellspacing="0">
<tr>
<td>Name:</td>
<td>
<input type="text" asp-for="Name" />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="text" asp-for="Age" />
</td>
</tr>
<tr>
<td>Address:</td>
<td>
<input type="text" asp-for="Address" />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>