【问题标题】:AJAX Request to MVC Controller with DataTable as Parameter以 DataTable 为参数向 MVC 控制器发出 AJAX 请求
【发布时间】:2013-07-04 12:11:53
【问题描述】:

如何将DataTable 作为参数传递给控制器​​。当我使用以下代码时,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 始终为空。有什么问题吗?

【问题讨论】:

  • 这行不通,因为模型绑定器不知道如何处理 DataTable 对象。如果您真的想做这件事,那么您必须自己编写一个自定义模型绑定器。
  • @Yellowfog,你能给出一些想法吗?

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


【解决方案1】:

如果您真的想要 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);
    }
}

【讨论】:

    【解决方案2】:

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

    public class Notification
    {
       public int UserId { get; set; }
       public int[,] Profiles { get; set; }
    }
    
    Content-Type: application/json
    {
        UserId: 1,
        Profiles: [[1,2]]
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多