Nepethya Rana

Nepethya Rana

  • NA
  • 335
  • 152k

How do i pass date from ajax to my method in mvc?

Oct 12 2017 9:00 PM
I have a view with date field. I have used pickaday.js for rendering date control.
on select even of date i need to update my model with the date.
my code is :
<div style="margin-top:8px; margin-bottom:8px;">
<span>Project Complete Date : </span>
<input type="text" class="form-control" style="display:inline-block;width:120px;height:25px;"
id="projectCompleteDate" data-projId="[email protected]" value="@Model.Project.ProjectCompleteDate"/>
</div>
<link href="~/Content/pikaday.css" rel="stylesheet" />
<script src="~/Scripts/pikaday.js"></script>
<script>
var picker = new Pikaday({
field: document.getElementById('projectCompleteDate'),
minDate: new Date(),
maxDate: new Date(2020, 12, 31),
yearRange: [2000, 2020],
format: 'M/D/YYYY',
onSelect: function (date) {
var projId = $(this).attr("data-projId");
var datVal = date;
updateProjectWithProjectCompleteDate(projId, datVal);
}
});
function updateProjectWithProjectCompleteDate(projId, datVal) {
var token = $('[name=__RequestVerificationToken]').val();
var projectID = $("#bodycert").attr("data-projectid");
debugger;
console.log(datVal)
$.ajax({
url: "/MyController/updateProjectWithReadyToOpenDate",
type: 'POST',
headers: { "__RequestVerificationToken": token },
data: {
"ProjectCompleteDate": new Date(datVal),
"ID": projectID
},
error: function (xhr, status, err) {
try {
// some code for logging error
logerror(e);
});
}
catch (err) {
}
}
}).done(function (data) {
});
}
</script>
Method in controller:
[HttpPost]
[ValidateAntiForgeryTokenAjax]
public void updateProjectWithReadyToOpenDate(Project proj)
{
var user = us.GetCurrentUser();
var bb = HasAccessToProject(user.Username,proj.ID);
if (bb == true)
{
using (var dbcontext = new MyDbContext())
{
var projId = proj.ID;
var project = dbcontext.Projects.Where(p => p.ID == proj.ID).FirstOrDefault();
if (project != null)
{
project.ProjectCompleteDate = proj.ProjectCompleteDate;
}
dbcontext.SaveChanges();
}
}
}
I get ID value but ProjectCompleteDate is coming null.
Please help. I need both date and time to update my model.

Answers (10)