使用DataTable作为参数的AJAX请求MVC控制器

时间:2013-07-04 12:11:53

标签: c# asp.net-mvc-4

如何将DataTable作为参数传递给Controller。当我使用下面的代码时,data总是为空。

对象

public class Notification
{
   public int UserId { get; set; }
   public DataTable Profiles { get; set; }
}

控制器

[HttpPost]
public HttpResponseMessage UpdateNotification(Notification data)
{
   if(data == null)
   {
        //data is always null here
   }
}

通过POSTMAN申请

Content-Type: application/json

{
    UserId: 1,
    Profiles: [1,2]
} 

当我删除Profiles时,它运行正常。但是在获得参数时,data始终为空。这有什么问题吗?

2 个答案:

答案 0 :(得分:0)

只需将DataTable更改为可从模型绑定器中获知的数组。 样品:

public class Notification
{
   public int UserId { get; set; }
   public int[,] Profiles { get; set; }
}

Content-Type: application/json
{
    UserId: 1,
    Profiles: [[1,2]]
} 

答案 1 :(得分:0)

如果你真的想要DataTable,我会很快敲掉一些东西,但它不是最好的代码:

这会在方法中连接新的模型绑定器:

public ActionResult UpdateNotification([ModelBinder(typeof(CustomModelBinder))] Notification data)
{
    ....
} 

指定

public class CustomModelBinder : DefaultModelBinder
{

     protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        if (propertyDescriptor.Name == "Profiles")
        {
            string vals = controllerContext.HttpContext.Request.Form["Profiles[]"];
            Notification notificiation = (Notification)bindingContext.Model;
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("ID", typeof(int)));
            notificiation.Profiles = table;
            foreach (string strId in vals.Split(",".ToCharArray()))
            {
                int intId;
                if (int.TryParse(strId, out intId))
                {
                    DataRow dr = table.NewRow();
                    dr[0] = intId;
                    table.Rows.Add(dr);
                }
            }
        }

        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }
}