1

How to pass DataTable as Parameter to Controller. The data is always null when i use the below code.

Object

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

Controller

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

Request through POSTMAN

Content-Type: application/json

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

When i remove Profiles, it is working fine. But on having the parameter the data is always null. Whats an issue with it?

4

2 回答 2

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);
    }
}
于 2013-07-05T09:54:12.370 回答
0

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

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

Content-Type: application/json
{
    UserId: 1,
    Profiles: [[1,2]]
} 
于 2013-07-05T09:40:10.347 回答