我无法获得POST参数排序。这是什么类型的?如何正确排序"排序"参数?我尝试了使用sender属性的对象,数组,特定对象,但没有任何帮助。
帖子正文:
current=1&rowCount=10&sort[sender]=asc&searchPhrase=&id=b0df282a-0d67-40e5-8558-c9e93b7befed
代码:
[HttpPost]
public ActionResult OrganizationPosts( int current, int rowCount, string sort = null, string searchPhrase = null )
{
return Json(
new {
current = 1,
rowCount= 10,
rows = new[]{
new { id= 16, post = "post 16" },
new { id= 117, post = "post 17"},
new { id= 19, post = "post 19"}
},
total = 1123
});
}
答案 0 :(得分:2)
模型绑定器不会绑定sort [sender]进行排序,如果您将请求更改为sort = asc,它将起作用。
如果您还需要发件人,只需添加发件人,将其添加为单独的参数,即:
current=1&rowCount=10&sort=asc&sender=someSender&searchPhrase=&id=b0df282a-0d67-40e5-8558-c9e93b7befed
并将方法签名更改为:
public ActionResult OrganizationPosts( int current, int rowCount, string sort = null, string sender = null, string searchPhrase = null)
如果您无法更改请求,则必须创建自定义模型绑定器: 这是一个可以提供帮助的链接:http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder
答案 1 :(得分:1)
我已修复此问题
public class SortDirection
{
public string prop { get; set; }
public string direction { get; set; }
}
public class CampaignModel
{
public int id { get; set; }
public string post { get; set; }
public string description { get; set; }
}
public class SortModelBinder
:System.Web.Mvc.IModelBinder
{
Type currType = typeof( CampaignModel );
public object BindModel( ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext )
{
HttpRequestBase request = controllerContext.HttpContext.Request;
var retVal = new SortDirection();
foreach( var prop in currType.GetProperties() )
{
string dir = request.Form.Get( string.Format( "sort[{0}]", prop.Name ) );
if( !string.IsNullOrEmpty( dir ) )
{
retVal.prop = prop.Name;
retVal.direction = dir;
}
}
return retVal;
}
}
public ActionResult OrganizationPosts( int current, int rowCount, [ModelBinder( typeof( SortModelBinder ) )] SortDirection sort, string sender = null, string searchPhrase = null )
{
...
}
答案 2 :(得分:1)
Andriy,我喜欢你的解决方案,但是为了我的需要,我把它变得更通用了,所以我们不需要为系统中的每个网格制作单独的ModelBinder。
public class BootgridSortModelBinder<T> : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
Type typeParameterType = typeof(T);
foreach (var prop in typeParameterType.GetProperties())
{
string dir = request.Form.Get(string.Format("sort[{0}]", prop.Name));
if (!string.IsNullOrEmpty(dir))
{
return new BootgridSortDirection() { prop = prop.Name, direction = dir };
}
}
return null;
}
}
然后在Controller中:
public string GetJsonGridData(int current, int rowCount, [ModelBinder(typeof(BootgridSortModelBinder<SomeModel>))] BootgridSortDirection sort, string searchPhrase = null)