当我的 JavaScript 与我的 cshtml 文件在同一个页面时,这是有效的:
function SaveEntity() {
// more code here
alert(entity.FirstName); // this shows that entity's properties have values
$.post('/Home/Save', { entity: entity }, SaveComplete);
}
该代码现在位于单独的 Index.js 文件中。在我的 Controller 中,实体参数不为空,但它的所有值都是。为什么现在会发生这种情况?
Controller 签名:
public ActionResult Save(Entity entity)
{ // method here }
编辑 - Fiddler 屏幕截图
编辑
这是由 Entity Framework 生成的实体类:
public partial class Entity
{
public Entity()
{
this.Contacts = new HashSet<Contact>();
}
public int EntityId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Company { get; set; }
public string LastModifiedUser { get; set; }
public Nullable<System.DateTime> LastModifiedTime { get; set; }
public string Notes { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
编辑
完整的 Index.js,带有完整的 SaveEntity() 方法:
var _currentEntities;
$(function () {
// Hide the ID column (column 1)
$('#tableContacts').dataTable({
"aoColumnDefs": [
{ "bSearchable": false, "bVisible": false, "aTargets": [0] }
],
"bLengthChange": false, // don't show the number of records to show per page
"bFilter": false, // don't show the search/filter box
"iDisplayLength": 5
});
$('#waitImage').hide();
// Show the letters of the alphabet, with a link to call GetEntries() for each of them.
for (var i = 65; i <= 90; i++) {
$('#headerAlphabet').append('<a href=\"#\" onclick=\"GetEntries(\''
+ String.fromCharCode(i) + '\')\">'
+ String.fromCharCode(i) + '</a> ');
}
});
function GetEntries(firstLetter) {
// code here
}
function EntriesReceived(entities) {
// code here
}
function DisplayPerson(entityId) {
// code here
}
function SaveEntity() {
// Grab our entity
var entity;
for (var i = 0; i < _currentEntities.length; i++) {
if (_currentEntities[i].EntityId == $('#txtEntityId').val()) {
entity = _currentEntities[i];
break;
}
}
entity.FirstName = $('#txtFirstName').val();
entity.LastName = $('#txtLastName').val();
entity.Address = $('#txtAddress').val();
entity.City = $('#txtCity').val();
entity.State = $('#txtState').val();
entity.ZipCode = $('#txtZipCode').val();
entity.Company = $('#txtCompany').val();
entity.Notes = $('#txtNotes').val();
alert(entity.FirstName);
$.post('/Home/Save', { entity: entity }, SaveComplete);
}
function SaveComplete(saveStatus) {
alert(saveStatus);
}
function CancelChanges() {
alert('Cancel will be done here.');
}
请您参考如下方法:
首先,在进行任何类型的 ajax 提交时,您需要在 Http 调试器(如 Fiddler)中查看实际请求。你想看看它是否真的发布了你认为的值。这将帮助您确定问题是出在您的 javascript 中还是在服务器上。现在,您还不知道。
其次,您应该发布您的服务器端实体定义。
编辑:
这似乎是 jQuery 默认序列化对象的方式存在问题,它使用方括号表示法,它不适用于默认模型联编程序。您必须使用 Dave 提到的传统:true 参数。
更多信息 Here .以下将解决您的问题。 $.param 方法与 true 参数一起使用时将强制进行传统序列化。
$.post('/Home/Save', $.param(entity, true), SaveComplete);.
