Gaurav Raj

Gaurav Raj

  • NA
  • 475
  • 88.2k

in MVC pass null value and undefine

Sep 3 2018 12:43 AM
This is my code
 
view
<div class="row">
<div class="col-md-8 col-lg-offset-4" >
<h2>Add New User</h2><br />
<span>Employee Name </span>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })<br />
<span>Employee Position</span>@Html.TextBoxFor(x => x.Position, new { @class = "form-control" })<br />
<span>Employee Office</span>@Html.TextBoxFor(x => x.Office, new { @class = "form-control" })<br />
<span>Employee Salary</span>@Html.TextBoxFor(x => x.Salary, new { @class = "form-control" })<br />
<a class="btn btn-default" onclick="saveUser();">Save User</a>
</div>
@*<div class="col-md-4 col-lg-offset-4">
<span>Employee Name</span>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })<br />

</div>*@

</div>
<div class="row">

<div class="col-md-8 col-lg-offset-3">
<h2>New User List</h2>
<table id="myTable" class="table table-striped" >
<tr>
<th>Employee Name</th>
<th>Employee Positio</th>
<th>Employee Office</th>
<th>Employee Salary</th>
</tr>
</table>

</div>
</div>

<style>
#myTable th{
background-color:yellowgreen;
color:white;
text-decoration:solid;
}
</style>
<script>

function saveUser() {
var name = $("#Name").val();
var position = $("#Position").val();
var office = $("#Office").val();
var salary = $("#Salary").val();
$.ajax({
type: 'POST',
url: '/Home/AddUser/',
data: JSON.stringify({ Name: name, Position: position, Office: office, Salary: salary }),
content: "application/json",
success: function (data) {
$("#myTable").append("<tr><td>" + data.name + "</td>" +
"<td>" + data.Position + "</td>" +
"<td>" + data.Office + "</td>" +
"<td>" + data.Salary + "</td></tr>");
console.log(data)
},
});
}
</script>
 
 
 
 
Controller
 
 
[HttpPost]
public ActionResult AddUser(string Name, string Position, string Office, string Salary)
{
Employee emp=new Employee();
emp.Name = Name;
emp.Position = Position;
emp.Office = Office;
emp.Salary =Convert.ToInt32(Salary);
db.Employees.Add(emp);
db.SaveChanges();
return Json(emp, JsonRequestBehavior.AllowGet);

Answers (4)