C# 使用DataTable作为参数向MVC控制器发出AJAX请求
如何将数据表作为参数传递给控制器。当我使用下面的代码时,C# 使用DataTable作为参数向MVC控制器发出AJAX请求,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,如何将数据表作为参数传递给控制器。当我使用下面的代码时,数据始终为空 对象 public class Notification { public int UserId { get; set; } public DataTable Profiles { get; set; } } 控制器 [HttpPost] public HttpResponseMessage UpdateNotification(Notification data) { if(data == null)
数据
始终为空
对象
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
}
}
通过邮递员请求
Content-Type: application/json
{
UserId: 1,
Profiles: [1,2]
}
当我删除
配置文件时,它工作正常。但是在使用参数时,数据
始终为空。它有什么问题吗?只需将数据表更改为可以从model binder中了解的数组即可。
样本:
如果您真的想要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);
}
}
这是行不通的,因为模型绑定器不知道如何处理DataTable对象。如果你真的想做这件事,那么你必须给自己写一个定制的模型活页夹。@Yellowfog,你能给我一些想法吗?
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);
}
}