我正在尝试编辑表中已经存在的值。当我单击条目行旁边的编辑按钮时,我希望这些值的原始值出现在表单的输入字段中,并且当我更改某些内容时,应对其进行编辑,否则将保持不变。现在可以正常工作了,只是日期将null传递给后端控制器。我已经签入调试器。
查看:
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-3 control-label" for="name">Date Of Birth </label>
<div class="col-sm-9">
<input type="text" id="dob" maxlength="30" ng-model="userAccount.dateOfBirth" class="form-control datepicker required" required>
</div>
</div>
</div>
Angular.js:
$scope.UserSave = function () {
debugger
$scope.userAccount.dateOfBirth = $('#dob').val();
$scope.userAccount.CountryID = $('#countryoptions').val();
Post("/User/Change", $scope.userAccount, false, $("#btnSave")).then(function (d) {
if (d.Success) {
window.location.href = "/User/LoggedIn";
}
ShowMessage(d);
});
}
Generic.cs:
function Post(url, data, isBlockUI, e) {
BlockUI(isBlockUI, e);
return $.ajax({
method: "Post",
url: url,
// contentType: 'application/json',
data: data,//JSON.stringify(data),
success: function (d) {
UnBlockUI(e);
if ($.type(d) == "string" && d == "")
LogOutNotification()
else if ($.type(d) == "string")
AccessDenied();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
UnBlockUI(e);
ErrorMessage(errorMsg);
}
});
}
我制作了一个单独的函数来处理从后端发送和接收的数据,如上所述,我知道它的工作正常,因为我正在使用它将数据添加到数据库中。
但是现在出现了我的问题。此数据将传递到控制器,并且传递的数据除日期外都可以。日期为空,我不知道为什么。由于在输入数据时db中的date字段设置为非null,因此我遇到了例外。
控制器:
public JsonResult Change(Account account) {
return Json((new userLogic()).Change(account), JsonRequestBehavior.AllowGet);
}
在调试时,我在这里检查account.dateofbirth属性的值并将其设置为1/1/0001,据我所知,日期格式为null。所以在尝试保存到数据库时出现错误。
逻辑:
public Message Change(Account account) {
Message msg = new Message();
try
{
Account userProfile = db.Accounts.Where(b => b.Email == account.Email).FirstOrDefault();
var dob = account.dateOfBirth;
if (userProfile == null)
{
msg.Success = false;
msg.MessageDetail = "somehting went wrong could not find the data entry amke sure the database connection is working";
}
else {
userProfile.firstName = account.firstName;
userProfile.lastName = account.lastName;
userProfile.Email = account.Email;
userProfile.password = account.password;
userProfile.CountryID = account.CountryID;
userProfile.dateOfBirth = account.dateOfBirth;
userProfile.phoneNo = account.phoneNo;
db.Entry(userProfile).State = EntityState.Modified;
db.SaveChanges();
msg.Success = true;
msg.MessageDetail = "Edit successful";
}
}
catch (Exception ex) {
msg.Success = false;
msg.MessageDetail = "somehting went wrong could not find the data entry make sure the database connection is working";
}
return msg;
}
当我将对象的数据发送到控制器时,我知道问题出在哪里。但是我似乎找不到我的错误,我只是以类似的方式添加数据,只是更改了后端的逻辑,所以似乎运行良好。
来自浏览器“网络”标签的数据显示了AJAX请求中发送的内容:
URL编码:
IsPermissionUpdated: false
UserId: 12
password: 88888888
firstName: Ali
lastName: Shujaat
Email: Ali%40gmail.com
CountryID: 6
phoneNo: 3244183346
dateOfBirth: 28%2F08%2F2018
isActive: true
Country:
Password: 97533284
URL解码:
IsPermissionUpdated: false
UserId: 12
password: 88888888
firstName: Ali
lastName: Shujaat
Email: Ali@gmail.com
CountryID: 6
phoneNo: 3244183346
dateOfBirth: 28/08/2018
isActive: true
Country:
Password: 97533284
添加数据的代码:由于我使用的是完全相同的方法,因此效果很好。
查看:
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-3 control-label" for="name">Date Of Birth </label>
<div class="col-sm-9">
<input type="text" id="dob" maxlength="30" ng-model="userAccount.dateOfBirth" class="form-control datepicker required" required>
</div>
</div>
</div>
角度:
$scope.UserSave = function () {
$scope.userAccount.dateOfBirth = $('#dob').val();
$scope.userAccount.CountryID = $('#countryoptions').val();
Post("/User/Save", $scope.userAccount , false, $("#btnSave")).then(function (d) {
if (d.Success) {
}
ShowMessage(d);
});
}
控制器:
public JsonResult Save(Account account) {
return Json((new userLogic()).Save(account), JsonRequestBehavior.AllowGet);
}
Logic.cs:
public Message Save(Account account)
{
Message msg = new Message();
// Account userProfile = Static.UserProfile;
try
{
Account foundaccount = db.Accounts.SingleOrDefault(x => x.Email == account.Email);
if (foundaccount != null)
{
msg.Success = false;
msg.MessageDetail = "Email already exist.";
}
else
{
Country c1 = db.Countries.Find(account.CountryID);
Account newaccount = new Account();
//newaccount.UserId = account.UserId;
newaccount.firstName = account.firstName;
newaccount.lastName = account.lastName;
newaccount.Email = account.Email;
newaccount.password = account.password;
newaccount.phoneNo = account.phoneNo;
newaccount.dateOfBirth = account.dateOfBirth;
newaccount.CountryID = account.CountryID;
newaccount.isActive = true;
//newaccount.Country = c1;
db.Accounts.Add(newaccount);
//db.Entry(newaccount).State = EntityState.Added;
db.SaveChanges();
msg.MessageDetail = account.Email + "has been saved";
}
//userProfile.LogActivity("Save", msg.MessageDetail, "EmploymentType");
}
catch (Exception ex)
{
msg.Success = false;
msg.MessageDetail = Message.ErrorMessage;
// userProfile.LogError(ex, "BLL/EmploymentTypeLogic/Save");
}
return msg;
}
}
我遇到的异常:
Message = "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."
答案 0 :(得分:0)
我发现了问题。 Jao和ADyson很好地了解了错误的根源。日期返回给控制器的格式是错误的。每次我选择dd-mm-yyyy格式的日期(其中dd大于13时)都会给我一个错误,所有低于该日期的内容都会起作用,因为c#中的datetime是mm-dd-yyyy。这就是为什么我遇到错误。
$scope.UserSave = function () {
//debugger
var convertedDate = $('#dob').val();
var splitdate = convertedDate.split('/');
var year1 = splitdate[2];
var month1 = splitdate[1];
var day1 = splitdate[0];
var date = month1 + "/" + day1 + "/" + year1;
$scope.userAccount.dateOfBirth = date;
$scope.userAccount.CountryID = $('#countryoptions').val();
Post("/User/Change", $scope.userAccount, false, $("#btnSave")).then(function (d) {
if (d.Success) {
window.location.href = "/User/LoggedIn";
}
ShowMessage(d);
});
}
将日期格式化为mm / dd / yyyy可以完全解决该问题。要注意的另一件事是,首先,因为我从表中获取的数据为json数据。 Json以另一种格式存储日期,因此,如果我不编辑日期字段。格式将完全不同,并且将引发相同的异常。因此,在显示数据之前先对其进行格式化是一个更好的选择。
答案 1 :(得分:-1)
在MVC视图中,当将日期直接呈现到稍后传递给操作的HTML元素(绕过模型状态)中时,请使用ISO日期格式MyDate.ToString(“ o”)。回传后,MVC会将日期正确解释回控制器操作中
使用“隐藏”字段和Ajax的示例
@Html.Hidden("SelectedMonth", Model.SelectedMonth.ToString("o"), new { @id = "hfSelectedMonth" })
JavaScript示例
//-----------------------------------------
// the month being viewed
var selectedMonth = $("#hfSelectedMonth").val();
//-----------------------------------------
// get content from URL using Ajax
// Note use of TRADITIONAL is required to pass the array to get a list of strings at the server
// ACTION with selected users parameter used
//-----------------------------------------
$.ajax({
url: "/SomeController/SomeAction/",
type: "get",
traditional: true,
data: { selectedMonth: selectedMonth, selectedUserIds: selectedUserIds },
success: function (result) {
$("#divWhereTheResultGoes").html(result);
}
});