Hi Ah1970,
Check this example. Now please take its reference and correct your code.
To allow insert with null value you need to chek the column value with null and set the DBNull.Value.
Model
public class Employee
{
public string empname { get; set; }
public string empcode { get; set; }
public string sponer { get; set; }
public string job { get; set; }
public DateTime jondt { get; set; }
public DateTime visadt { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
public bool myempsave(Employee em)
{
int i = 0;
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO employeemaster VALUES(@Name,@Code,@Sponcer,@Job,@JoinDate,@VisaDate)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@Name", em.empname);
cmd.Parameters.AddWithValue("@Code", em.empcode);
cmd.Parameters.AddWithValue("@Sponcer", em.sponer);
cmd.Parameters.AddWithValue("@Job", em.job != null ? em.job : (object)DBNull.Value);
cmd.Parameters.AddWithValue("@JoinDate", em.jondt != DateTime.MinValue ? em.jondt : DateTime.Now);
cmd.Parameters.AddWithValue("@VisaDate", em.visadt != DateTime.MinValue ? em.visadt : (object)DBNull.Value);
i = cmd.ExecuteNonQuery();
con.Close();
}
}
return Convert.ToBoolean(i);
}
}
View
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#Savedata1').click(function () {
var colc = {
empname: $('#name1').val(),
empcode: $('#code1').val(),
sponer: $('#sponsorname').val(),
job: $('#jobTitl').val(), //Null
jondt: $('#hideJoindate').val(),
visadt: $('#hideVisadate').val()// Null
}
$.ajax({
url: '/Home/myempsave',
type: 'post',
data: colc,
success: function (dat2) {
if (dat2 == "True") {
alert("Data Save successfully")
}
else {
alert("This Data is already used!!!")
}
},
error: function (err) {
alert("not working")
}
})
});
});
</script>
</head>
<body>
<div>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name1" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" id="code1" /></td>
</tr>
<tr>
<td>Sponser</td>
<td><input type="text" id="sponsorname" /></td>
</tr>
<tr>
<td>Job</td>
<td><input type="text" id="jobTitl" /></td>
</tr>
<tr>
<td>Join Date</td>
<td><input type="text" id="hideJoindate" /></td>
</tr>
<tr>
<td>Visa Date</td>
<td><input type="text" id="hideVisadate" /></td>
</tr>
</table>
<br />
<input type="button" value="Save" id="Savedata1" />
</div>
</body>
</html>
Screenshot

Inserted Database Record
