【问题标题】:Posting value to web api method from ajax call why going null?从 ajax 调用将值发布到 web api 方法为什么会为空?
【发布时间】:2018-02-27 10:10:34
【问题描述】:

当我调试它显示空值时,我将一些值发布到 Web API 方法。

下面是 ajax 调用的片段代码,这里我传递了dept_name,但它在 Web API 方法中显示为 null。

var _customer = {};
            _customer.DepartmntName = txtName.val();
            _customer.DateCreated = null;
            _customer.DateModified = null;
            _customer.IsDeleted = null;
            _customer.ParentID = null;
            _customer.Icon = null;
            _customer.Paren = null;
            alert( _customer.DepartmntName);
            alert(_customer);
            $.ajax({
                type: "POST",
                url: "/api/AddDepSpc/InsertCustomer2",
                 data: JSON.stringify(_customer),
                contentType: "application/json",
                dataType: "json",
                success: function (r) {
                alert("success" + r);
               var row = $("#tblCustomers tr:last-child").clone(true);
                    //AppendRow(row, r.CustomerId, r.Name, r.Country);
      AppendRow(row,r.dept_name.r.date_created,r.date_modified,r.IsDeleted,
       r.ParentID.r.Icon,r.Paren);
                    txtName.val("");

                }
            });

web api 方法的 sn-p 代码如下。

public class AddDepSpcController : ApiController
    {
        [Route("api/AddDepSpc/InsertCustomer2")]
        [HttpPost]
        public   master_department InsertCustomer2(master_department _customer)
        {           
            using (HRMEntities entities = new HRMEntities())
            {
                entities.master_department.Add(_customer);
                entities.SaveChanges();
                entities.SaveChanges();
            }
            return _customer;
        }      
    }

现在在调试模式下它显示 null 假设我已将 HR 作为部门名称传递,并且所有其余参数现在都为 null。期望 web api 方法中的 HR 参数值。

【问题讨论】:

  • 12id值从何而来?
  • 而且您的模型甚至不包含名为 DepartmntName 的属性(尽管有一个名为 dept_name 的属性)。事实上,您的帖子与您的模型有任何关系的唯一名称/值对是Icon
  • @StephenMuecke 它的身份列。
  • @StephenMuecke 表中没有关系,其他值允许为空,这样我就不会在 ajax 调用中发布,并且我的部门名称在表中插入为空
  • 当然是 - 您没有为名为 dept_name 的属性发送名称/值对。如果要将txtName 的值绑定到dept_name 属性,请使用_customer.dept_name = txtName.val();

标签: asp.net-mvc-4 asp.net-web-api asp.net-ajax asp.net-mvc-views


【解决方案1】:

您发回的对象包含与您的模型不匹配的属性名称。

您的模型包含一个名为 dept_name 的属性,但 javascript 对象包含一个名为 DepartmntName 的属性。同样,其他名称都不匹配(Icon 除外)。假设您要将txtName 的值绑定到模型dept_name 属性,然后在脚本中,使用

var _customer = {};
_customer.dept_name = txtName.val(); // not DepartmntName
....

还请注意,没有理由将null 值添加到_customer 对象(默认情况下它们在控制器中为null)。您也可以删除contentType: "application/json", 选项,只在ajax 调用中使用data: _customer, 而不是对其进行字符串化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 2021-09-02
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多