无法将Javascript对象绑定到动作控制器

时间:2015-08-11 19:35:55

标签: javascript jquery ajax model-view-controller

我似乎无法弄清楚如何让我的Javascript对象绑定到我的模型(据我所知)就像属性一样。

首先创建Javascript对象:

var transDetail = new Object();
transDetail.TransactionDetailID = transdetailId;
transDetail.TransactionID = "";
transDetail.Year = new Date().getFullYear();
transDetail.Volume = "";
transDetail.UnitPrice = "";
transDetail.TransferableVolume = "";
transDetail.Credits = "";
transDetail.Shares = "";
transDetail.DollarsPerShare = "";

然后传递给这个javascript函数

function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
    $.ajax(
        {
            url: '/TransactionDetail/LoadEditCreate',
            data: JSON.stringify(transactionDetail),
            dataType: 'json',
            success: function (result) {
                d.html(result);
                CreateEditTransDetail(d, cb, title, transactionDetail);
                d.dialog('open');
            }
        }
    );
}

我已经确认2015年之前的财产已经填满了。

现在是模型定义

public partial class TransactionDetail
{
    public int TransactionDetailID { get; set; }
    public int TransactionID { get; set; }
    public int Year { get; set; }
    public Nullable<int> Volume { get; set; }
    public Nullable<int> UnitPrice { get; set; }
    public Nullable<int> TransferableVolume { get; set; }
    public Nullable<int> Credits { get; set; }
    public Nullable<int> Shares { get; set; }
    public Nullable<int> DollarsPerShare { get; set; }

}

动作定义

public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)

当我将第一个东西分解为动作时,所有非可空的int都设置为0,并且所有可空的都设置为null。

1 个答案:

答案 0 :(得分:1)

问题在于发送数据:JSON ...

您有两个选择:

  1. 使用POST :(已尝试并正常工作)

    function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
    $.ajax(
        {
            type: 'post',                                      //added
            contentType: "application/json; charset=utf-8",    //added
            url: '/TransactionDetail/LoadEditCreate',
            data: JSON.stringify(transactionDetail),
            dataType: 'json',
            success: function (result) {
                d.html(result);
                CreateEditTransDetail(d, cb, title, transactionDetail);
                d.dialog('open');
            }
        }
      );
    }
    
  2. 并使用[HttpPost]属性

    装饰您的控制器
    [HttpPost]
    public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
    
    1. 如果你想使用get - look here(没有尝试,应该工作)