自定义模型绑定的复杂的复合对象帮助 [英] Custom Model Binder for Complex composite objects HELP
问题描述
我想写一个自定义的模型绑定,但我有很大的困难试图弄清楚如何绑定复杂的复合对象。
I am trying to write a custom model binder but I'm having great difficulty trying to figure how to bind complex composite objects.
这是我想要绑定到类:
public class Fund
{
public int Id { get; set; }
public string Name { get; set; }
public List<FundAllocation> FundAllocations { get; set; }
}
这就是我在编写定制绑定尝试的样子:
and this is how my attempt at writing the custom binder looks like:
public class FundModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
{
var fund = new Fund();
fund.Id = int.Parse(controllerContext.HttpContext.Request.Form["Id"]);
fund.Name = controllerContext.HttpContext.Request.Form["Name"];
//i don't know how to bind to the list property :(
fund.FundItems[0].Catalogue.Id = controllerContext.HttpContext.Request.Form["FundItem.Catalogue.Id"];
return fund;
}
}
任何想法
谢谢
托尼
推荐答案
你真的需要在这里实现自定义ModelBinder的?默认的粘结剂可以做你的需要(因为它可以填充集合和复杂的对象):
Do you really need to implement a custom ModelBinder here? The default binder may do what you need (as it can populate collections and complex objects):
比方说你的控制器动作看起来是这样的:
Lets say your controller action looks like this:
public ActionResult SomeAction(Fund fund)
{
//do some stuff
return View();
}
和你的HTML包含此:
And you html contains this:
<input type="text" name="fund.Id" value="1" />
<input type="text" name="fund.Name" value="SomeName" />
<input type="text" name="fund.FundAllocations.Index" value="0" />
<input type="text" name="fund.FundAllocations[0].SomeProperty" value="abc" />
<input type="text" name="fund.FundAllocations.Index" value="1" />
<input type="text" name="fund.FundAllocations[1].SomeProperty" value="xyz" />
默认的模型粘合剂应该与FundAllocations列表2项初始化你的基金的对象(我不知道你的FundAllocation类是什么样子,所以我做了一个单一的财产SomeProperty)。只是一定要包括那些fund.FundAllocations.Index元素(这默认粘结剂看它自己使用),这让我当我试图得到这个工作)。
The default model binder should initialise your fund object with 2 items in the FundAllocations List (I don't know what your FundAllocation class looks like, so I made up a single property "SomeProperty"). Just be sure to include those "fund.FundAllocations.Index" elements (which the default binder looks at for it's own use), that got me when I tried to get this working).
这篇关于自定义模型绑定的复杂的复合对象帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!