2

我有以下实体:

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。

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

4

2 回答 2

2

我在这个问题上发布了一个模型活页夹,它使用 IRepository 来填充外键(如果存在)。你可以修改它以更好地适应你的目的。

于 2010-09-03T16:42:07.153 回答
1

使用 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);
    }
}

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

于 2010-09-03T23:09:59.937 回答