当我的 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 文件中。在我的控制器中,实体参数不为空,但它的所有值都是。为什么现在会发生这种情况?
控制器签名:
public ActionResult Save(Entity entity)
{ // method here }
编辑 - Fiddler 截图
编辑
这是由 Entity Framework 生成的 Entity 类:
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.');
}