【问题标题】:ASP.NET MVC - Custom Model Binder for ID fieldsASP.NET MVC - ID 字段的自定义模型绑定器
【发布时间】:2013-10-29 19:19:23
【问题描述】:

我有以下实体:

public class Category
{
    public virtual int CategoryID { get; set; }

    [Required(ErrorMessage = "Section is required")]
    public virtual Section Section { get; set; }

    [Required(ErrorMessage = "Category Name is required")]
    public virtual string CategoryName { get; set; }
}

public class Section
{
    public virtual int SectionID { get; set; }
    public virtual string SectionName { get; set; }
}

现在在我的添加类别视图中,我有一个文本框可以输入 SectionID,例如:

<%= Html.TextBoxFor(m => m.Section.SectionID) %>

我想创建一个具有以下逻辑的自定义模型绑定器:

如果模型键以 ID 结尾并且有一个值(一个值被插入到文本框中),则将父对象(本例中的 Section)设置为 Section.GetById(value entered) 否则将父对象设置为 null。

非常感谢这里的帮助,因为这让我困惑了一段时间。谢谢

【问题讨论】:

    标签: asp.net-mvc modelbinders model-binding custom-model-binder


    【解决方案1】:

    我在this question 上发布了一个模型绑定器,它使用 IRepository 来填充存在的外键。您可以对其进行修改以更好地满足您的目的。

    【讨论】:

    • 感谢您的链接。到目前为止,它确实对我有帮助。如果您可以查看我尝试的解决方案并帮助完成它,将不胜感激:)。
    【解决方案2】:

    使用 dave thieben 发布的解决方案,我提出了以下建议:

    public class CustomModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            if (bindingContext.ModelType.Namespace.EndsWith("Models.Entities") && value != null && (Utilities.IsInteger(value.AttemptedValue) || value.AttemptedValue == ""))
            {
                if (value.AttemptedValue != "")
                    return Section.GetById(Convert.ToInt32(value.AttemptedValue));
                else
                    return null;
            }
            else
                return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    这很好用,但是当表单被回发并使用下拉列表时,它不会选择正确的值。我明白为什么,但到目前为止,我修复它的尝试都是徒劳的。如果您能提供帮助,我将再次感谢您。

    【讨论】:

    • 如果你还在做这个,在if 语句中你有value.AttemptedValue == "",然后在下一行你有value.AttemptedValue != "",所以看起来它永远不会到达你的Section.GetById() 代码。
    • 再次为您的建议喝彩,但逻辑是正确的,即使它可以进行一些整理以使其更具可读性。该问题的解决方案是创建一个处理 SelectItem 的 Selected 属性的自定义 DropDownList。希望他们能在下一个 MVC 版本中修复这个错误。
    • 我有一个自定义模型绑定器view it here,它尝试对属性进行排序,以便始终首先绑定标识字段。我让实际的视图模型类——在它的属性设置器中——触发它自己的存储库加载,而不是让自定义绑定器来做。 (重新阅读您的 O.P. 后,我意识到这并不完全合适,但是,也许会给其他人一个想法)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多