【问题标题】:What am I doing wrong in trying to create a model binder?我在尝试创建模型活页夹时做错了什么?
【发布时间】:2011-05-25 20:52:21
【问题描述】:

我有这个模型:

public class QuestionSimple
    {
        public string Body { get; set; }
        public bool IsSingleChoice { get; set; }
        public List<String> Answers { get; set; }
        public string Difficutly { get; set; }
        public string Explanation { get; set; }

    }  

我尝试在Global.asax.cs中使用这一行进行绑定

ModelBinders.Binders.Add(typeof(QuestionSimple), new AddQuestionSimpleBinder());  

...有了这个活页夹

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            // Get the raw attempted value from the value provider    
            string key = bindingContext.ModelName;
            ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);  
            //val is ALWAYS NULL
            return null;
        }  

但 val 始终为空。
这是当我使用我的活页夹时应该返回(实际上确实返回)答案列表的视图。

 @using (Html.BeginForm("AddQuestionSimple", "Topic", FormMethod.Post, new { @id = "mainForm" }))
    {    
        <input type="text" name="questionToBeAdded.Answers[0]" value="ff" />
        <input type="text" name="questionToBeAdded.Answers[1]" value="ddds" />
        <input type="text" name="questionToBeAdded.Answers[2]" value="ff" />
        <input type="text" name="questionToBeAdded.Answers[3]" value="ddds" />
        <input type="text" name="questionToBeAdded.Answers[4]" value="ff" />
        <input type="text" name="questionToBeAdded.Answers[5]" value="ddds" /> 
        <input value="Add question" type="submit" style="position: static; width: 10em; height: 3em;
            font-size: 1em;" />
    }   

当我发布它们时,默认的模型绑定器确实会获取我的值,但我的 val 始终是 null
为什么会这样?
(应该提到这是解决this更大问题的尝试)。

编辑 1:
这是应该绑定的动作

   [HttpPost]
   public ActionResult AddQuestionSimple(PMP.WebUI.Models.UserInteractionEntities.UserInput.QuestionSimple questionToBeAdded)
    {
        return View("AddQuestion");
    }

谢谢。

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    首先,您必须重写 BindModel,因此您的方法应以:

    public override object BindModel
    

    接下来,您不会在 bindingContext.ValueProviders 中找到键为“questionToBeAdded”的值。调试并查看该集合,bindingContext.ValueProviders[1] 有一个 FormValueProvider,其中包含模型的所有属性。你这样做的方式,你可能不得不手动迭代。另一种方法是重写 BindProperty 方法,只需键入:

    protected override void BindProperty
    

    在您的模型绑定器类中,您将获得填充的方法签名(假设您从 DefaultModelBinder 继承)。在这种方法中,您将获得有关每个属性的更多详细信息,管道已为您完成。

    【讨论】:

    • 'public override object BindModel' 给出编译时错误 - 没有合适的方法被覆盖。 (我正在实现 IModelBinder)。还应该提到调试器在没有使用“覆盖”的情况下确实到达了我的活页夹,并且“bindingContext.ValueProviders[1]”给出:...ModelBindingContext 不包含“ValueProviders”的定义..
    • 哦,是的,我假设您是从 DefaultModelBinder 继承的。如果没有,只需忽略覆盖修饰符。但我建议您继承 DefaultModelBinder 以开始使用自定义活页夹。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多