【问题标题】:Getting null values on attributes of inner class获取内部类属性的空值
【发布时间】:2013-05-26 10:01:18
【问题描述】:

我有以下使用内部类的 KnockoutJS 映射:

public class Retailer
{
    public int RetailerId { get; set; }
    public string DemoNumber { get; set; }
    public string OutletName { get; set; }
    public string OwnerName { get; set; }
    public Address Address { get; set; }

    public Logging Logging { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zipcode { get; set; }
    public string Mobile { get; set; }
    public string LandLine { get; set; }
    public string Email { get; set; }
}

上面显示了我的模型,我正在使用 KnockoutJS 构建我的网站。

我可以使用ko.mapping 插件绑定控件。但是,当我尝试插入 Retailer 的值时,内部类 Address 正在返回所有属性的 null 值。

当我在客户端测试时,它会显示整个模型值。

IdeaSales.NewRetailer = function () {
    $.ajax({
        url: '/Retailer/Retailer',
        dataType: 'json',
        cache: false,
        type: "post",
        success: function (data) {
            viewModel = ko.mapping.fromJS(data);
            ko.applyBindings(viewModel);
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });
}

IdeaSales.InsertRetailer = function () {
    var newModel = ko.toJS(viewModel);
    $.ajax({
        url: '/Retailer/InsertRetailer',
        data:viewModel,
        cache: false,
        type: "post",
        success: function (data) {

        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });
}    

还有:

public int InsertRetailer(Retailer retailer)
{
    return new RetailerAppService().InsertRetailer(retailer);
}

问题是我正在获取零售商信息,但对于 Address 类,我正在获取每个 Null 值。

【问题讨论】:

  • 你在发data:viewModel,你不是打算发data:newModel吗?无论如何,如果您检查该 POST 并查看发送到服务器的内容会有所帮助:这是您所期望的吗?
  • MVC 模型绑定将初始化动作中的所有参数,然后尝试将发布的值与发布的对象绑定。在构造时,retailer 中 address 的默认值为 null ,就像 jeroen 所说的那样,无论如何你看起来在帖子中传递了错误的值,因此,retailer 将只是所有内容的默认值。
  • 好的!但是在将模型传递给服务器时,我可以传递零售商信息,但地址信息为空

标签: jquery asp.net-mvc knockout.js knockout-mapping-plugin


【解决方案1】:

当您向服务器发送 JSON 时,您需要指定 内容类型。

这个版本的 InsertRetailer 应该可以工作:

IdeaSales.InsertRetailer = function () {
    var newModel = ko.toJS(viewModel);
    $.ajax({
        url: '/Retailer/InsertRetailer',
        contentType: "application/json",
        data: newModel,
        cache: false,
        type: "post",
        success: function (data) {

        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多